<?php require_once(BASEPATH.'application/controllers/validaciones.php');
class comp extends Controller {

	function comp(){
		parent::Controller();
		$this->load->library('rapyd');
		$this->load->library('Cuenta');
		
	}
	function index(){
		redirect("supervisor/comp/filteredgrid");
	}
	function filteredgrid(){
		
		$this->rapyd->load("datagrid","dataform","fields");

		$control=$this->uri->segment(4);
		$checkbox =  '<input type="checkbox" name="genera[]" value="<#tcomp#>">';

		$grid = new DataGrid('Comprobantes a Generar');
		$grid->db->select('modulo, descrip,tcomp');
		$grid->db->from('modulos');
		$grid->db->orderby('id');

		$grid->column("Seleccione"        , $checkbox );
        $grid->column("Comprobante"       , "tcomp" );
		$grid->column("Descripci&oacute;n", "descrip");
		//$grid->column('Generar'    , $checkbox,'align="center"');
		$grid->build();

		$form = new DataForm('supervisor/comp/procesar');
		
		$form->title('Rango de fecha para la Generaci&oacute;n');
		$form->fechai = new dateonlyField("Fecha Desde", "fechai","Y-m-d");
		$form->fechaf = new dateonlyField("Fecha Hasta", "fechaf","Y-m-d");
		$form->fechaf->size = $form->fechai->size=10;
		$form->fechaf->insertValue =($this->input->post('fechaf') ? $this->input->post('fechaf') : date("Ymd"));
		
		$form->tabla= new containerField('tabla',$grid->output);
		if ($control) $form->control= new containerField('control','Contabilidad Generada');
		$form->build_form();
		
		$form->submit("btnsubmit","Generar");
		$form->build_form();
		
		$data['content'] = $form->output;
		$data['filtro']  = ' ';
		$data["head"]    = $this->rapyd->get_head();
		$data['title']   =heading("Generar Comprobantes");
		$this->load->view('view_ventanas', $data);
	}
    function busqsiigo(){
    
        $this->rapyd->load('datagrid2','datafilter');
        $this->rapyd->uri->keep_persistence();
        
        function formato($tabla='',$compro='',$id=''){
			
			$atts = array(
				'width'      => '1100',
				'height'     => '700',
				'scrollbars' => 'yes',
				'status'     => 'yes',
				'resizable'  => 'yes',
				'screenx'    => '200',
				'screeny'    => '0'
			);
			
			
			
            
            switch ($tabla) {
                case 'gser': 
                $id =str_pad($id, 11, "0", STR_PAD_LEFT);
                $uri= anchor_popup("finanzas/gastos/dataedit/show/$id",$compro,$atts);	
                return($uri);
                break;
                case 'remision': 
                $uri= anchor_popup("ventas/sfacdesfyco/dataedit/show/$id",$compro,$atts);	
                return($uri);
                break;
                case 'sfac': 
                $uri= anchor_popup("ventas/sfac/dataedit/show/$id",$compro,$atts);	
                return($uri);
                break;
                case 'itppro': 
                $uri= anchor_popup("finanzas/sprm/dataedit/show/$id",$compro,$atts);	
                return($uri);
                break;
                case 'itpprot': 
                $uri= anchor_popup("finanzas/sprm/dataedit/show/$id",$compro,$atts);	
                return($uri);
                break;
                case 'itabonos': 
                $uri= anchor_popup("ventas/smov/dataedit/show/$id",$compro,$atts);	
                return($uri);
                break;
                case 'bmov': 
                $uri= anchor_popup("ventas/bmov/dataedit/show/$id",$compro,$atts);	
                return($uri);
                break;
                case 'letras': 
                $uri= anchor_popup("ventas/abonos/dataedit/show/$id",$compro,$atts);	
                return($uri);
                break;
                case 'itcruce': 
                $id =str_pad($id, 11, "0", STR_PAD_LEFT);
                $uri= anchor_popup("finanzas/cruce/dataedit/show/$id",$compro,$atts);	
                return($uri);
                break;
                case 'notascc': 
                $uri= anchor_popup("ventas/notasc/dataedit/show/$id",$compro,$atts);	
                return($uri);
                break;
                case 'notascp': 
                $uri= anchor_popup("finanzas/notasc/dataedit/show/$id",$compro,$atts);	
                return($uri);
                break;
                case 'notasdc': 
                $uri= anchor_popup("ventas/notasd/dataedit/show/$id",$compro,$atts);	
                return($uri);
                break;
                case 'ssal': 
                $uri= anchor_popup("inventario/ssal/dataedit/show/$id",$compro,$atts);	
                return($uri);
                break;
                case 'scst': 
                $uri= anchor_popup("compras/scst/dataedit/show/$id",$compro,$atts);	
                return($uri);
                break;
                default:   return($compro); 
            };
         
        }
		 
		$modbus=array(
			'tabla'   =>'cpla',
			'columnas'=>array(
				'cuenta'  =>'Cuenta',
				'descrip' =>'Descripci&oacute;n',
				'ajuste'  => 'Llevar Ajuste',
				'contrapartida'  => 'Contrapartida',
				'clase'  => 'Clase',
				'costo'  => 'Costo',
				'tercero'  => 'Tercero',
				'extranjeria'  => 'Extranjeria'
				),
			'filtro'  =>array('cuenta'  =>'Cuenta','descrip'=>'Descripci&oacute;n'),
			'retornar'=>array(
				'cuenta' =>'cuenta'),
			'p_uri'   => array(4=>'<#i#>'),
			'titulo'  => 'Buscar Cuenta'
		);
		$btn=$this->datasis->p_modbus($modbus);
        
        
        $filter = new DataFilter('B&uacute;squeda de Comprobantes');
        $select=array("estampac","id","tabla","cuenta","dc","nit","descrip","cambio","fecha","CONCAT(tcomp,ccomp,'-',ncomp)AS compro","CONCAT(tdoc_cruce,ccomp_cruce,'-',num_cruce)AS cruce","secuencia secu",
        "IF(dc='D',monto,0)montods",
        "IF(dc='C',monto,0)montocs",
        "IF(dc='D',monto_me,0)montodd",
        "IF(dc='C',monto_me,0)montocd");
        
		$filter->db->select($select);
		$filter->db->from("comprobantes AS a");
        $filter->db->where("tcomp <>",'A');
        
        $ano=date("Y");
        
        $filter->fechad = new dateonlyField('Desde', 'fechad','d/m/Y');
		$filter->fechah = new dateonlyField('Hasta', 'fechah','d/m/Y');
		$filter->fechad->clause  =$filter->fechah->clause ='where';
		$filter->fechad->db_name =$filter->fechah->db_name='fecha';
		$filter->fechad->insertValue = date("Y-m-d", mktime(0, 0, 0, 01, 1, $ano));
		$filter->fechah->insertValue = date('Y-m-d');
		$filter->fechah->size=$filter->fechad->size=10;
		$filter->fechad->operator='>=';
		$filter->fechah->operator='<=';

		$filter->cuenta = new inputField('Cuenta', 'cuenta');
		$filter->cuenta->size = 20;
        $filter->cuenta->append($btn);

        $filter->tcomp = new inputField('Letra de Comprobante', 'tcomp');
		$filter->tcomp->size=20;
        
        $filter->ccomp = new inputField('Serie de Comprobante', 'ccomp');
		$filter->ccomp->size=20;
        
        $filter->ncomp = new inputField('Numero de Comprobante', 'ncomp');
		$filter->ncomp->size=20;
        
        $filter->tdoc_cruce = new inputField('Letra de Documento cruce', 'tdoc_cruce');
		$filter->tdoc_cruce->size=20;
        
        $filter->ccomp_cruce = new inputField('Serie cruce', 'ccomp_cruce');
		$filter->ccomp_cruce->size=20;
        
        $filter->num_cruce = new inputField('Numero cruce', 'num_cruce');
		$filter->num_cruce->size=20;
        
        $filter->dc = new inputField('Naturaleza', 'dc');
		$filter->dc->size=20;

		$filter->buttons('reset','search');
		$filter->build();

		$grid = new DataGrid2();
		$grid->order_by('ncomp','desc');
		$grid->per_page = 30;
        $grid->use_function('formato');
        
        $grid->column("Comprobante"  ,'<formato><#tabla#>|<#compro#>|<#id#></formato>','align=center');        
        //$grid->column_orderby('Comprobante','compro','compro',"align='center'");
        $grid->column_orderby('Cuenta','cuenta','cuenta',"align='center'");
        $grid->column_orderby('Ruc','nit','nit',"align='center'");
		$grid->column_orderby('Secuencia' ,'secu','secu',"align='center'");
        $grid->column_orderby('DC','dc','dc',"align='center'");
		$grid->column_orderby("Cruce","cruce","cruce"  ,"align='center'");
		$grid->column_orderby('Debitos S/.','<nformat><#montods#></nformat>' ,'montods','align=\'right\'');
        $grid->column_orderby('Creditos S/.','<nformat><#montocs#></nformat>' ,'montocs','align=\'right\'');
        $grid->column_orderby('Debitos $','<nformat><#montodd#></nformat>' ,'montodd','align=\'right\'');
        $grid->column_orderby('Creditos $','<nformat><#montocd#></nformat>' ,'montocd','align=\'right\'');
        $grid->column_orderby('Cambio','<nformat><#cambio#></nformat>' ,'cambio','align=\'right\'');
        $grid->column_orderby('Fecha','<dbdate_to_human><#fecha#></dbdate_to_human>'     ,'fecha'  );
        $grid->column_orderby('Glosa','descrip','descrip',"align='left'");
        $grid->column_orderby('Origen','tabla','tabla',"align='left'");
        $grid->column_orderby('Estampa','estampac','estampac',"align='left'");
        
		$grid->totalizar('montods','montocs','montodd','montocd');
        $grid->build('datagridST');
		//echo $grid->db->last_query();
        
		$style ='
		<style type="text/css">
		.fakeContainer { /* The parent container */
		    margin: 5px;
		    padding: 0px;
		    border: none;
		    width: 1500px; /* Required to set */
		    height: 600px; /* Required to set */
		    overflow: hidden; /* Required to set */
		}
		</style>	
		';
			
		$data['script']  = script('jquery.js');
		$data['style']   = $style;
		$data['style']  .= style('superTables.css');
		$data['script'] .= script('superTables.js');
		       
		$data['filtro']  = $filter->output;
		$data['content'] = $grid->output;
		
		$data['head']    = $this->rapyd->get_head();
		$data['title'] = heading('Buscar Comprobantes');
		$this->load->view('view_ventanas', $data);
    }
	function procesar(){
        
        //INSERT INTO saldoi (fecha,dc,cuenta,descrip,monto,monto_me)
        //SELECT '2012-12-31' fecha,a.dc,a.cuenta,b.descrip,IF(dc='D',sum(monto),sum(monto*-1))monto,
        //IF(dc='D',sum(monto_me),sum(monto_me*-1)) monto_me
        //FROM comprobantes as a
        //JOIN cpla as b on a.cuenta=b.cuenta
        //WHERE a.fecha <= '2012-12-31' 
        //GROUP BY a.cuenta,a.dc 
		

		$fechai=$this->input->post('fechai');
		$fechaf=$this->input->post('fechaf');
        
        $genera=$this->input->post('genera');
        
        $cant=count($genera);
          
        $i=$o=0;
         
		while($o<$cant){
			
            $array=array('0'=>$genera[$i]);
                    
            switch ($genera[$i]){
			
            case 'F':
                $this->_f($fechai,$fechaf);//Factura de Venta
                break;
            
            case 'C':
                $this->_c($fechai,$fechaf);//Factura de Venta	
                break;
            
            case 'D':
                $this->_d($fechai,$fechaf);//Factura de Venta	
                break;
            
            case 'P':
                $this->_p($fechai,$fechaf);//Factura de Venta	
                break;
            
            case 'CNI':
                $this->_cni($fechai,$fechaf);//Factura de Venta	
                break;
            
            case 'L':
                $this->_l($fechai,$fechaf);//Factura de Venta
                break;
                
            case 'LL':
                $this->_l2($fechai,$fechaf);//Factura de Venta	
                break;
            
            case 'G':
                $this->_g($fechai,$fechaf);//Factura de Venta	
                break;
                
            case 'R':
                $this->_r($fechai,$fechaf);//Factura de Venta	
                break;
        
            }       
            $i++;
			$o++;
		}
        
        //$this->_c($fechai,$fechaf);//Notas de Credito
        //$this->_d($fechai,$fechaf);//Notas de Debito
        //$this->_p($fechai,$fechaf);//Facturas de Compra
        //$this->_cni($fechai,$fechaf);//Compra nacional y internacional
        //$this->_l($fechai,$fechaf);//Letras
        //$this->_s($fechai,$fechaf);//Guia de remision
        //$this->_r($fechai,$fechaf);//Recibos
        //$this->_g($fechai,$fechaf);//Egresos
        //$this->_f($fechai,$fechaf);//Factura de Venta
		
		$this->rapyd->load("datafilter","datagrid2");
		$this->rapyd->uri->keep_persistence();
		
		$atts = array(
			'width'      => '800',
			'height'     => '600',
			'scrollbars' => 'yes',
			'status'     => 'yes',
			'resizable'  => 'yes',
			'screenx'    => '0',
			'screeny'    => '0'
		);
		
		
		$filter = new DataFilter('Los registros generados se deben descargar por tipo de comprobante','comprobantes');

		$filter->fechad = new dateonlyField('Desde', 'fechad','Y-m-d');
		$filter->fechah = new dateonlyField('Hasta', 'fechah','Y-m-d');
		$filter->fechad->clause  =$filter->fechah->clause='where';
		$filter->fechad->db_name =$filter->fechah->db_name='fecha';
		$filter->fechad->insertValue = $fechai; 
		$filter->fechah->insertValue = $fechaf; 
		$filter->fechah->size=$filter->fechad->size=10;
		$filter->fechad->operator='>='; 
		$filter->fechah->operator='<=';
				
		$filter->tcomp = new dropdownField("Tipo de Comprobante", "tcomp");
		$filter->tcomp->style='width:180px;';
		$filter->tcomp->option("F",'Factura de Venta'); 
		$filter->tcomp->option("P",'Facturas de Compras'); 
		$filter->tcomp->option("G",'Pagos a Proveedores'); 
		$filter->tcomp->option("R",'Pagos de Clientes'); 
		$filter->tcomp->option("L",'Letras'); 
		//$filter->tcomp->option("NC",'Notas de  Cr&eacute;dito'); 
		//$filter->tcomp->option("ND",'Notas de D&eacute;bito'); 
		$filter->tcomp->style='width:220px;';
		
		$filter->serie = new inputField("N&deg; Serie","ccomp");
		$filter->serie->size=10;
		$filter->serie->maxlength=3;

		$filter->numero = new inputField('N&uacute;mero', 'ncomp');
		$filter->numero->size = 10;
		
		$filter->buttons('reset','search');
		$filter->build();
		
		if($this->rapyd->uri->is_set("search")){
			
			$fechai=$filter->fechad->newValue; 
			$fechaf=$filter->fechah->newValue; 
			
			
			$uri = anchor_popup("xlsauto/comprobantes/$fechai/$fechaf/",img(array('src'=>'images/view_text.gif','border'=>'0','alt'=>'Descargar','height'=>'15','title'=>'Descargar')),$atts);
	        $uri .= anchor_popup("reportes/ver/COMPROTXT/",img(array('src'=>'images/reportes.gif','border'=>'0','alt'=>'Descargar','height'=>'15','title'=>'Descargar')),$atts);
	
			$grid = new DataGrid2('Descargar Comprobantes '.$uri);
			$grid->order_by('tcomp','DESC');
			$grid->per_page = 10;
	
			
			$grid->column('Comp-','tcomp');
			$grid->column('D/C','dc');
			$grid->column('Serie','ccomp');
			$grid->column('N&uacute;mero','ncomp');
			$grid->column('Cliente/Proveedor','nit');
			$grid->column('Cuenta','cuenta');
			$grid->column('Codigo','cprod');
			$grid->column('Descripci&oacute;n','descrip');
			$grid->column('Cant','cant');
			$grid->column('Monto','monto');
			$grid->column('Moneda','moneda');
			$grid->column('Cambio','cambio');
			$grid->column('Monto. Extranjera','monto_me');
			$grid->column('Doc. Cruce','tdoc_cruce');
			$grid->column('Cod. Cruce','ccomp_cruce');
			$grid->column('Num. Cruce','num_cruce');
			$grid->column('Forma de Pago','formap');
			$grid->column('Medio de Pago','cod_mpago');
			//$grid->column('Banco','cbanco');
			$grid->column('Tip. Pedido','tdoc_pedido');
			$grid->column('Cod. Pedido','ccom_pedido');
			$grid->column('Num. Pedido','num_pedido');

			$grid->build();
			//echo $grid->db->last_query();
	
			$data['content'] = $grid->output;
		
		}
		
		 $style ='
		<style type="text/css">
		.fakeContainer { /* The parent container */
		    margin: 5px;
		    padding: 0px;
		    border: none;
		    width: 1000px; /* Required to set */
		    height: 300px; /* Required to set */
		    overflow: hidden; /* Required to set */
		}
		</style>	
		';
		
        $data['style']   = $style;
		$data['filtro']  = $filter->output;
		$data['tabla']  = "";
		
		$data['head']    = $this->rapyd->get_head();
		$data['title'] = heading('Comprobantes Generados');
		$this->load->view('view_ventanas', $data);

		
	}
    function _r($fechai,$fechaf){
        
        $this->db->query("DELETE FROM comprobantes WHERE tcomp='R' AND fecha BETWEEN '$fechai' AND '$fechaf' AND tabla<>'siigo'");
		
		//***********************************************
        //*//Otros movimientos de bancos 
        
        $query_2=$this->db->query("SELECT id FROM bmov WHERE fecha BETWEEN '$fechai' AND '$fechaf' AND cajero='2' AND clipro='C' AND formap<>'0003'");
        
        foreach($query_2->result() as $items2 ){
            
            $G_c="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia, cuenta,  
            fdocu, descrip,  dc,  monto, 
            cambio,  monto_me, cod_mpago, fecha,cheque,nit)	
            SELECT a.id,'bmov' as tabla, b.moneda,IF(clipro='P','G','R')As tcomp,a.banco,numero,'00001'AS secu,b.cuenta,
            DATE_FORMAT(fecha, '%Y%m%d')fecha, a.observacion as descrip,IF(a.clipro='P','C','D')dc,
            LPAD(ROUND(a.montos,2),16,0) monto,
            INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
            LPAD(ROUND(a.montod,2),16,0) montoe,
            RIGHT (formap,3) cod_formap,fecha,LPAD(a.referencia,11,'0')referen,LPAD(a.brif,13,0) ruc
            FROM bmov AS a
            JOIN bancos as b on a.banco=b.codigo
            WHERE a.id='$items2->id'";
            
            $this->db->query($G_c);
            
             $query_3=$this->db->query("SELECT idt FROM itbmov WHERE id='$items2->id'");
              
              $i=2;
              foreach($query_3->result() as $items3 ){
				
				$secu2=STR_PAD($i,5,0,STR_PAD_LEFT); 
				
				$G_d="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia, cuenta,  
				fdocu, descrip,  dc,  monto, 
				cambio,  monto_me, cod_mpago, fecha,cheque,nit)	
				SELECT a.id,'bmov' as tabla, a.moneda,IF(clipro='P','G','R')As tcomp,a.banco,numero,'$secu2'AS secu,b.cuenta,
				DATE_FORMAT(fecha, '%Y%m%d')fecha, b.desca as descrip,b.tipo as dc,
				if(a.moneda='01',LPAD(ROUND(a.monto,2),16,0),LPAD(ROUND(a.monto*a.cambio,2),16,0)) monto,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
				IF(a.moneda='02',LPAD(a.monto,16,0),LPAD(ROUND(a.monto/a.cambio,2),16,0)) montoe,
				RIGHT (formap,3) cod_formap,fecha,LPAD(a.referencia,11,'0')referen,LPAD(b.ruc,13,0) ruc
				FROM itbmov AS b
				JOIN bmov as a on a.id=b.id
				WHERE b.idt='$items3->idt'";
					
				$this->db->query($G_d);
				$i++;
			  }
            
            
        }
        
        //**********************************************************	
		//Genera Comprobantes R 		
		
		$query=$this->db->query("SELECT id,moneda FROM itabonos WHERE fecha BETWEEN '$fechai' AND '$fechaf' AND tipo='AB'");
		
		foreach($query->result() as $items ){
			
		$query_2=$this->db->query("SELECT id FROM cobros WHERE itabono='$items->id' AND tipo<>'NC' AND numero NOT IN ('R000%')");
		
		$chek1=$this->datasis->dameval("SELECT intbanco  FROM itabonos WHERE id='$items->id'");
		$chek2=$this->datasis->dameval("SELECT comibanco FROM itabonos WHERE id='$items->id'");
		
		$secu2=$query_2->num_rows();
		$secu2=$secu2+1;
		$secu2=STR_PAD($secu2,5,0,STR_PAD_LEFT);
        
		$i=1;
								
		foreach($query_2->result() as $detalle ){
		
		$secu1=STR_PAD($i,5,0, STR_PAD_LEFT);
		$ii   =STR_PAD($i,3,0, STR_PAD_LEFT);	
        
        $cuentaRI=$this->cuenta->antic($items->moneda);		
		
				$R_c="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp, ccomp,  ncomp,  secuencia,  nit, cuenta,  
				fdocu,  ccost,  descrip,  dc,  monto,   czona, tdoc_cruce, 
				ccomp_cruce,  num_cruce,  sec_cruce, cambio,  monto_me,  cod_mpago, fecha,tip_letra,est_letra,n,fven_cruce,doc_banco,cheque)	
				SELECT a.id,'itabonos'as tabla,a.moneda, 'R',a.serie,a.numero,'$secu1' AS secu,
				IF(d.rifci IS NULL,LPAD(a.rif,13,0),LPAD(d.rifci,13,0)) ruc,c.cuenta,
				DATE_FORMAT(a.fecha, '%Y%m%d')fecha,ccosto,
				IF(b.tipo  IN ('CONTADO','LIBRE'),CONCAT('COBRO DE FACTURA ',b.serie,'-',b.numero),IF(b.tipo='RI','REINTEGRO ENTREGAS A RENDIR',CONCAT('COBRO DE LETRA ',c.control)))as descrip,'C',
				IF(a.moneda=c.moneda,if(a.moneda='01',LPAD(ROUND(b.monto,2),16,0),LPAD(ROUND(b.monto*a.cambio,2),16,0)),if(a.moneda='01',LPAD(ROUND(a.monto,2),16,0),LPAD(ROUND(a.monto*a.cambio,2),16,0)))monto,
				'001'zona,
				IF(b.tipo NOT IN ('CONTADO','LIBRE','ND','RI'),'L',IF(b.tipo='ND','D',IF(b.tipo='RI','G','F')))as doc_cruce,
                IF(b.tipo NOT IN ('CONTADO','LIBRE','ND','RI'),'LTR',IF(b.tipo='RI',(SELECT i.serie FROM itppro as i where i.id=c.id_rein),'001')) serie_cruce,
			    IF(b.tipo NOT IN ('CONTADO','LIBRE','ND','RI'),c.control,IF(b.tipo='RI',(SELECT i.numero FROM itppro as i where i.id=c.id_rein),b.numero)) num_cruce,'$ii' sec_cruce,
				INSERT(LPAD(a.cambio,12,0), 13,13, '0000') cambio,
				IF(a.moneda=c.moneda,IF(a.moneda='01',LPAD(ROUND(b.monto/a.cambio,2),16,0),LPAD(b.monto,16,0)),IF(a.moneda='01',LPAD(ROUND(a.monto/a.cambio,2),16,0),LPAD(a.monto,16,0)))montoe,
				RIGHT (a.formap,3) cod_formap,a.fecha, 'L', 'A', 'N',DATE_FORMAT(c.vence, '%Y%m%d')
				,LPAD(referen,12,'0')doc_banco,LPAD(referen,12,'0')cheque
				FROM itabonos AS a
				JOIN cobros   AS b ON a.id=b.itabono
				JOIN itpagos  AS c ON b.idpago=c.id
				LEFT JOIN scli     AS d ON b.cod_cli=d.cliente
				WHERE b.id='$detalle->id' AND b.tipo<>'NC' and b.tipod='R'";
				
				$this->db->query($R_c);
				//echo $R_c.'</br>';
				
				$i++;
			}
												
			$R_d="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
			fdocu,  ccost,  descrip,  dc,  monto,   cciud,  czona, 
			cambio,  monto_me, cod_mpago, fecha,doc_banco,cheque)	
			SELECT  a.id,'itabonos'as tabla,moneda,'R',serie,numero,'$secu2'AS secu,LPAD(rif,13,0) ruc,cuenta,
			DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto, 
			a.condi1 as descrip,'D',
			if(a.moneda='01',LPAD(ROUND(a.montob,2),16,0),LPAD(ROUND(a.montob*a.cambio,2),16,0)) monto,
			'0001'ciudad,'001' zona,
			INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			IF(moneda='01',LPAD(ROUND(a.montob/cambio,2),16,0),LPAD(a.montob,16,0)) montoe,
			RIGHT (formap,3) cod_formap,fecha,LPAD(referen,12,'0')doc_banco,LPAD(referen,12,'0')cheque	
			FROM itabonos as a WHERE a.id='$items->id'";
			
			$this->db->query($R_d);	
			
			
			IF($chek1 >0){
				
			$secu2=$query_2->num_rows();
			$secu2=$secu2+2;
			$secu2=STR_PAD($secu2,5,0,STR_PAD_LEFT);	
				
				$R_d="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
				fdocu,  ccost,  descrip,  dc,  monto,   cciud,  czona, 
				cambio,  monto_me, cod_mpago, fecha,doc_banco,cheque)	
				SELECT  a.id,'itabonos'as tabla,moneda,'R',serie,numero,'$secu2'AS secu,LPAD(rif,13,0) ruc,'7702020000',
				DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto, 
				CONCAT('INTERESES DE BANCO ',serie,'-',numero)as descrip,'C',
				if(a.moneda='01',LPAD(ROUND(a.intbanco,2),16,0),LPAD(ROUND(a.intbanco*a.cambio,2),16,0)) monto,
				'0001'ciudad,'001' zona,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
				IF(moneda='01',LPAD(ROUND(a.intbanco/cambio,2),16,0),LPAD(a.intbanco,16,0)) montoe,
				RIGHT (formap,3) cod_formap,fecha,LPAD(referen,12,'0')doc_banco,LPAD(referen,12,'0')cheque	
				FROM itabonos as a WHERE a.id='$items->id'";
				
				$this->db->query($R_d);		
				
			}
			
			IF($chek2 >0){
				
			$secu=$query_2->num_rows();
			
			$secu2=$secu+3;
			$secu3=$secu+4;
			$secu4=$secu+5;
			$secu2=STR_PAD($secu2,5,0,STR_PAD_LEFT);
			$secu3=STR_PAD($secu3,5,0,STR_PAD_LEFT);
			$secu4=STR_PAD($secu4,5,0,STR_PAD_LEFT);
			
				
				$R_d="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
				fdocu,  ccost,  descrip,  dc,  monto,   cciud,  czona, 
				cambio,  monto_me, cod_mpago, fecha,doc_banco,cheque)	
				SELECT  a.id,'itabonos'as tabla,moneda,'R',serie,numero,'$secu2'AS secu,LPAD(rif,13,0) ruc,'9563090100',
				DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto, 
				CONCAT('GASTO DE BANCO ',serie,'-',numero)as descrip,'D',
				if(a.moneda='01',LPAD(ROUND(a.comibanco,2),16,0),LPAD(ROUND(a.comibanco*a.cambio,2),16,0)) monto,
				'0001'ciudad,'001' zona,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
				IF(moneda='01',LPAD(ROUND(a.comibanco/cambio,2),16,0),LPAD(a.comibanco,16,0)) montoe,
				RIGHT (formap,3) cod_formap,fecha,LPAD(referen,12,'0')doc_banco,LPAD(referen,12,'0')cheque	
				FROM itabonos as a WHERE a.id='$items->id'";
				
				$this->db->query($R_d);
				
				$R_A="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
				fdocu,  ccost,  descrip,  dc,  monto,   cciud,  czona, 
				cambio,  monto_me, cod_mpago, fecha,doc_banco,cheque)	
				SELECT  a.id,'itabonos'as tabla,moneda,'R',serie,numero,'$secu3'AS secu,LPAD(rif,13,0) ruc,'6309010000',
				DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto, 
				CONCAT('PAGO DE FACTURA ',serie,'-',numero)as descrip,'D',
				if(a.moneda='01',LPAD(ROUND(a.comibanco,2),16,0),LPAD(ROUND(a.comibanco*a.cambio,2),16,0)) monto,
				'0001'ciudad,'001' zona,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
				IF(moneda='01',LPAD(ROUND(a.comibanco/cambio,2),16,0),LPAD(a.comibanco,16,0)) montoe,
				RIGHT (formap,3) cod_formap,fecha,LPAD(referen,12,'0')doc_banco,LPAD(referen,12,'0')cheque	
				FROM itabonos as a WHERE a.id='$items->id'";
				
				$this->db->query($R_A);
				
				$R_CO="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
				fdocu,  ccost,  descrip,  dc,  monto,   cciud,  czona, 
				cambio,  monto_me, cod_mpago, fecha,doc_banco,cheque)	
				SELECT  a.id,'itabonos'as tabla,moneda,'R',serie,numero,'$secu4'AS secu,LPAD(rif,13,0) ruc,'7901010000',
				DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto, 
				CONCAT('CARGOS IMPUTABLES A CUENTAS DE COSTOS ')descrip,'C',
				if(a.moneda='01',LPAD(ROUND(a.comibanco,2),16,0),LPAD(ROUND(a.comibanco*a.cambio,2),16,0)) monto,
				'0001'ciudad,'001' zona,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
				IF(moneda='01',LPAD(ROUND(a.comibanco/cambio,2),16,0),LPAD(a.comibanco,16,0)) montoe,
				RIGHT (formap,3) cod_formap,fecha,LPAD(referen,12,'0')doc_banco,LPAD(referen,12,'0')cheque	
				FROM itabonos as a WHERE a.id='$items->id'";
				
				$this->db->query($R_CO);		
				
			}
		
			
		}
        
         //*********ANTICIPOS A CLIENTES************
		
		$query=$this->db->query("SELECT id,moneda,rein FROM itabonos WHERE fecha BETWEEN '$fechai' AND '$fechaf' AND tipo='AN'");
		
		foreach($query->result() as $items ){
			
			$cuenta=$this->cuenta->antic($items->moneda);		
			
			$R_c="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp, ccomp,  ncomp,  secuencia,  nit, cuenta,  
			fdocu,  ccost,  descrip,  dc,  monto,   czona, tdoc_cruce, 
			ccomp_cruce,  num_cruce,  sec_cruce, cambio,  monto_me,  cod_mpago, fecha,fven_cruce,cheque)	
			SELECT a.id,'itabonos'as tabla,a.moneda, 'R',a.serie,a.numero,'00001' AS secu,LPAD(rif,13,0) ruc,'$cuenta'cuenta,
			DATE_FORMAT(a.fecha, '%Y%m%d')fecha,ccosto,
			IF(condi1='',CONCAT('ANTICIPO DE CLIENTE CREADO ',a.serie,'-',a.numero),CONCAT('ANTICIPO ',a.condi1)) as descrip, 
			'C',
			if(a.moneda='01',LPAD(ROUND(a.montob,2),16,0),LPAD(ROUND(a.montob*a.cambio,2),16,0)) monto,
			'001'zona,
			'R'as doc_cruce,
			a.serie as serie_cruce,a.numero num_cruce,'001' sec_cruce,
			INSERT(LPAD(a.cambio,12,0), 13,13, '0000') cambio,
			IF(a.moneda='01',LPAD(ROUND(a.montob/a.cambio,2),16,0),LPAD(a.montob,16,0)) montoe,
			RIGHT (formap,3) cod_formap,a.fecha, DATE_FORMAT(a.fecha, '%Y%m%d'),LPAD(referen,12,'0')cheque
			FROM itabonos AS a
			WHERE a.id='$items->id' AND tipo='AN'";
			
			$this->db->query($R_c);
			
			//**cuenta de banco
			
			$R_d="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp, ccomp,  ncomp,  secuencia,  nit, cuenta,  
			fdocu,  ccost,  descrip,  dc,  monto,   czona,cambio,  monto_me,  cod_mpago, fecha,fven_cruce,cheque)	
			SELECT a.id,'itabonos'as tabla,a.moneda, 'R',a.serie,a.numero,'00002' AS secu,LPAD(rif,13,0) ruc,a.cuenta,
			DATE_FORMAT(a.fecha, '%Y%m%d')fecha,ccosto,
			a.condi1 as descrip, 
			'D',if(a.moneda='01',LPAD(ROUND(a.montob,2),16,0),LPAD(ROUND(a.montob*a.cambio,2),16,0)) monto,
			'001'zona,INSERT(LPAD(a.cambio,12,0), 13,13, '0000') cambio,
			IF(a.moneda='01',LPAD(ROUND(a.montob/a.cambio,2),16,0),LPAD(a.montob,16,0)) montoe,
			RIGHT (formap,3) cod_formap,a.fecha, DATE_FORMAT(a.fecha, '%Y%m%d')
			,LPAD(referen,12,'0')doc_banco
			FROM itabonos AS a
			WHERE a.id='$items->id' AND tipo='AN'";
			
			$this->db->query($R_d);
			
		}
								
    }
    function _g($fechai,$fechaf){
       
       $this->db->query("DELETE FROM comprobantes WHERE tcomp='G' AND fecha BETWEEN '$fechai' AND '$fechaf' AND tabla<>'siigo'");
       
        //***********************************************
        //*//Otros movimientos de bancos 
        
        $query_2=$this->db->query("SELECT id FROM bmov WHERE fecha BETWEEN '$fechai' AND '$fechaf' AND cajero='2' AND clipro='P' AND formap<>'0003'");
        
        foreach($query_2->result() as $items2 ){
            
            $G_c="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia, cuenta,  
            fdocu, descrip,  dc,  monto, 
            cambio,  monto_me, cod_mpago, fecha,cheque,nit)	
            SELECT a.id,'bmov' as tabla, b.moneda,IF(clipro='P','G','R')As tcomp,a.banco,numero,'00001'AS secu,b.cuenta,
            DATE_FORMAT(fecha, '%Y%m%d')fecha, a.observacion as descrip,IF(a.clipro='P','C','D')dc,
            LPAD(ROUND(a.montos,2),16,0) monto,
            INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
            LPAD(ROUND(a.montod,2),16,0) montoe,
            RIGHT (formap,3) cod_formap,fecha,LPAD(a.referencia,11,'0')referen,LPAD(a.brif,13,0) ruc
            FROM bmov AS a
            JOIN bancos as b on a.banco=b.codigo
            WHERE a.id='$items2->id'";
            
            $this->db->query($G_c);
            
             $query_3=$this->db->query("SELECT idt FROM itbmov WHERE id='$items2->id'");
              
              $i=2;
              foreach($query_3->result() as $items3 ){
				
				$secu2=STR_PAD($i,5,0,STR_PAD_LEFT); 
				
				$G_d="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia, cuenta,  
				fdocu, descrip,  dc,  monto, 
				cambio,  monto_me, cod_mpago, fecha,cheque,nit)	
				SELECT a.id,'bmov' as tabla, a.moneda,IF(clipro='P','G','R')As tcomp,a.banco,numero,'$secu2'AS secu,b.cuenta,
				DATE_FORMAT(fecha, '%Y%m%d')fecha, b.desca as descrip,b.tipo as dc,
				if(a.moneda='01',LPAD(ROUND(a.monto,2),16,0),LPAD(ROUND(a.monto*a.cambio,2),16,0)) monto,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
				IF(a.moneda='02',LPAD(a.monto,16,0),LPAD(ROUND(a.monto/a.cambio,2),16,0)) montoe,
				RIGHT (formap,3) cod_formap,fecha,LPAD(a.referencia,11,'0')referen,LPAD(b.ruc,13,0) ruc
				FROM itbmov AS b
				JOIN bmov as a on a.id=b.id
				WHERE b.idt='$items3->idt'";
					
				$this->db->query($G_d);
				$i++;
			  }
            
            
        }
        
         //***********************************************
        //*//Transferencias entre bancos
        
        $query_2=$this->db->query("SELECT id FROM bmov WHERE fecha BETWEEN '$fechai' AND '$fechaf' AND cajero='2' AND clipro<>'T' AND formap='0003'");
        
        foreach($query_2->result() as $items2 ){
            
            $G_c="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia, cuenta,  
            fdocu, descrip,  dc,  monto, 
            cambio,  monto_me, cod_mpago, fecha,cheque,nit)	
            SELECT a.id,'bmov' as tabla, b.moneda,IF(clipro='P','G','R')As tcomp,a.banco,numero,'00001'AS secu,b.cuenta,
            DATE_FORMAT(fecha, '%Y%m%d')fecha, a.observacion as descrip,IF(a.clipro='P','C','D')dc,
            LPAD(ROUND(a.montos,2),16,0) monto,
            INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
            LPAD(ROUND(a.montod,2),16,0) montoe,
            RIGHT (formap,3) cod_formap,fecha,LPAD(a.referencia,11,'0')referen,LPAD(a.brif,13,0) ruc
            FROM bmov AS a
            JOIN bancos as b on a.banco=b.codigo
            WHERE a.id='$items2->id'";
            
            $this->db->query($G_c);
                          
            $i=2;
            $secu2=STR_PAD($i,5,0,STR_PAD_LEFT);
            
            $G_d="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia, cuenta,  
			fdocu, descrip,  dc,  monto, 
			cambio,  monto_me, cod_mpago, fecha,cheque,nit)	
			SELECT a.id,'bmov' as tabla, a.moneda,IF(clipro='P','G','R')As tcomp,a.banco,numero,'$secu2'AS secu,b.cuenta,
			DATE_FORMAT(fecha, '%Y%m%d')fecha, b.desca as descrip,b.tipo as dc,
			LPAD(ROUND(a.montos,2),16,0) monto,
			INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			LPAD(ROUND(a.montod,2),16,0) montoe,
			RIGHT (formap,3) cod_formap,fecha,LPAD(a.referencia,11,'0')referen,LPAD(b.ruc,13,0) ruc
			FROM itbmov AS b
			JOIN bmov as a on a.id=b.id
			WHERE a.id='$items2->id'";
				
			$this->db->query($G_d);
 
            
        }
        
        //*//*******************************************************	
		//*//Genera Comprobantes G 
		
		$query=$this->db->query("SELECT a.id,a.moneda,a.tipo,a.rein FROM itppro as a
		JOIN bancos as b on a.serie=b.codigo WHERE b.tipo<>'O' AND fecha BETWEEN '$fechai' AND '$fechaf' AND a.tipo NOT IN ('AN','AR','EC')");
		
		foreach($query->result() as $items ){
			
		$query_2=$this->db->query("SELECT id  FROM relacion WHERE itppro='$items->id' AND tipod='G'");
		$query_3=$this->db->query("SELECT idt FROM itpprot  WHERE id='$items->id'");
		
		
		$secu2=$query_2->num_rows();
		$secu2=$secu2+1;
		$secu2=STR_PAD($secu2,5,0,STR_PAD_LEFT);
        				
		$G_d="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
		fdocu,  ccost,  descrip,  dc,  monto, 
		cambio,  monto_me, cod_mpago, fecha,cheque,cvend)	
		SELECT a.id,'itppro' as tabla, moneda,'G',serie,numero,'00001'AS secu,LPAD(rif,13,0) ruc,cuenta,
		DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto, 
		a.condi1 as descrip,'C',
		if(a.moneda='01',LPAD(ROUND(a.monto,2),16,0),LPAD(ROUND(a.monto*a.cambio,2),16,0)) monto,
		INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(a.moneda='01',LPAD(ROUND(a.monto/a.cambio,2),16,0),LPAD(a.monto,16,0)) montoe,
		RIGHT (formap,3) cod_formap,fecha,LPAD(a.referen,11,'0')referen,'0000'	
		FROM itppro AS a	
		WHERE a.id='$items->id'";
		
		$this->db->query($G_d);
		
		$i=2;
						
		foreach($query_2->result() as $detalle ){
			
		$secu1=STR_PAD($i,5,0, STR_PAD_LEFT);
		$ii   =STR_PAD($i,3,0, STR_PAD_LEFT);
        
        $cuentaRI=$this->cuenta->antic($items->moneda);	
		
        $detra=$this->datasis->dameval("SELECT cod_prv FROM relacion WHERE id='$detalle->id' LIMIT 1");
        
            $G_c="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp, ccomp,  ncomp,  secuencia,  nit, cuenta,  
				fdocu,  ccost,  descrip,  dc,  monto,tdoc_cruce, 
				ccomp_cruce,  num_cruce,  sec_cruce, cambio,  monto_me,  cod_mpago, fecha,fven_cruce,cvend,cheque)	
				SELECT a.id,'itppro' as tabla,a.moneda,'G',a.serie,a.numero,'$secu1'AS secu,(SELECT LPAD(rif,13,0) from sprv as p where b.proveed=p.proveed) ruc,
				if((SELECT cuenta FROM gser as g WHERE c.transac=g.transac)IS NULL,(SELECT cuenta FROM scst as g WHERE c.transac=g.transac),(SELECT cuenta FROM gser as g WHERE c.transac=g.transac))cuenta,
				DATE_FORMAT(a.fecha, '%Y%m%d')fecha,'0002',
				RPAD(CONCAT('DOCUMENTO ',b.serief,'-',b.factura),50,' ')as descrip,'D',
				LPAD(ROUND(b.cmontos,2),16,0)monto,				
				'P'as doc_cruce,serief as serie_cruce,b.factura num_cruce,'$ii' sec_cruce,  
				INSERT(LPAD(a.cambio,12,0), 13,13, '0000') cambio,
				LPAD(ROUND(b.cmontod,2),16,0)montoe,	
				RIGHT (formap,3) cod_formap,a.fecha,DATE_FORMAT(c.vence, '%Y%m%d'),'0000',LPAD(a.referen,11,'0')referen	
				FROM itppro   AS a
				JOIN relacion AS b ON a.id=b.itppro
				JOIN sprm     AS c ON b.serief=c.seriep  AND b.factura=c.numero AND b.cod_prv=c.cod_prv AND concat(tipo_doc,seriei)<>'L005'              
				JOIN sprv     AS d ON b.cod_prv=d.proveed
				WHERE b.id='$detalle->id'";	
				
				$this->db->query($G_c);
				
				$i++;
        }
					
		
		foreach($query_3->result() as $detalle ){
			
		$secu2=STR_PAD($i,5,0, STR_PAD_LEFT);
		$ii   =STR_PAD($i,3,0, STR_PAD_LEFT);
					
								
			$G_o="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
			fdocu,  ccost,  descrip,  dc,  monto, 
			cambio,  monto_me, cod_mpago, fecha,cheque,cvend)
			SELECT a.id,'itpprot' as tabla, moneda,'G',serie,numero,'$secu2'AS secu,LPAD(trim(b.ruc),13,0) ruc,b.cuenta,
			DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto, 
			b.desca as descrip,b.tipo,
			if(a.moneda='01',LPAD(ROUND(b.importe,2),16,0),LPAD(ROUND(b.importe*a.cambio,2),16,0)) monto,
			INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			IF(a.moneda='01',LPAD(ROUND(b.importe/a.cambio,2),16,0),LPAD(b.importe,16,0)) montoe,
			RIGHT (formap,3) cod_formap,fecha,LPAD(a.referen,11,'0')referen,'0000'	
			FROM itppro AS a
			JOIN itpprot as b on a.id=b.id
			WHERE b.idt='$detalle->idt'";
			
			$this->db->query($G_o);
				
			$i++;
			
        }
        
       $query_1=$this->db->query("SELECT idt,cuenta FROM itpprot  WHERE id='$items->id' AND cuenta like '9%'");
              
       
       $m3=$i-1;
       $m4=$i; 
       
       foreach($query_1->result() as $items1 ){
		   
	   $m4=$m4+1; 
       $m3=$m3+1;
                     
       $m3=STR_PAD($m3,5,0, STR_PAD_LEFT);
       $m4=STR_PAD($m4,5,0, STR_PAD_LEFT); 
           		
			$ajuste=$this->datasis->dameval("SELECT ajuste FROM cpla WHERE cuenta='$items1->cuenta'");
			
            IF (!empty($ajuste)){		
			
            $P_aj="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
			fdocu,  ccost,  descrip,  dc,  monto, 
			cambio,  monto_me, cod_mpago, fecha,cheque,cvend)
			SELECT a.id,'itpprot' as tabla, moneda,'G',serie,numero,'$m3'AS secu,LPAD(trim(b.ruc),13,0) ruc,'$ajuste',
			DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto, 
			b.desca as descrip,'D',
			if(a.moneda='01',LPAD(ROUND(b.importe,2),16,0),LPAD(ROUND(b.importe*a.cambio,2),16,0)) monto,
			INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			IF(a.moneda='01',LPAD(ROUND(b.importe/a.cambio,2),16,0),LPAD(b.importe,16,0)) montoe,
			RIGHT (formap,3) cod_formap,fecha,LPAD(a.referen,11,'0')referen,'0000'	
			FROM itppro AS a
			JOIN itpprot as b on a.id=b.id
			WHERE b.idt='$items1->idt'";
			
			$this->db->query($P_aj);
            
            }
			
			$contrapartida=$this->datasis->dameval("SELECT contrapartida FROM cpla WHERE cuenta='$items1->cuenta'");
			
            IF (!empty($contrapartida)){
                
			$P_cont="INSERT INTO comprobantes(id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
			fdocu,  ccost,  descrip,  dc,  monto, 
			cambio,  monto_me, cod_mpago, fecha,cheque,cvend)
			SELECT a.id,'itpprot' as tabla, moneda,'G',serie,numero,'$m4'AS secu,LPAD(trim(b.ruc),13,0) ruc,'$contrapartida',
			DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto, 
			b.desca as descrip,'C',
			if(a.moneda='01',LPAD(ROUND(b.importe,2),16,0),LPAD(ROUND(b.importe*a.cambio,2),16,0)) monto,
			INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			IF(a.moneda='01',LPAD(ROUND(b.importe/a.cambio,2),16,0),LPAD(b.importe,16,0)) montoe,
			RIGHT (formap,3) cod_formap,fecha,LPAD(a.referen,11,'0')referen,'0000'	
			FROM itppro AS a
			JOIN itpprot as b on a.id=b.id
			WHERE b.idt='$items1->idt'";
					
			$this->db->query($P_cont);	
            
            }
            
            $m3++;
            $m4++;
        }	
        		
			
		}
        
        //***********ANTICIPOS DE PROVEEDORES*********
		
		$query=$this->db->query("SELECT id,moneda,rein FROM itppro WHERE fecha BETWEEN '$fechai' AND '$fechaf' AND tipo IN ('AN','EC')");
		
		foreach($query->result() as $items ){
			
		$cuenta=$this->cuenta->antip($items->moneda);			
								
			//*****cuenta de banco*********
							
			$G_c="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp, ccomp,  ncomp,  secuencia,  nit, cuenta,  
			fdocu,  ccost,  descrip,  dc,  monto,tdoc_cruce, 
			ccomp_cruce,  num_cruce,  sec_cruce, cambio,  monto_me,  cod_mpago, fecha,fven_cruce,cvend,cheque)	
			SELECT a.id,'itppro' as tabla,a.moneda,'G',a.serie,a.numero,'00001' AS secu,LPAD(rif,13,0) ruc, IF(a.cuenta_ori='',$cuenta,a.cuenta_ori) cuenta_ori,
			DATE_FORMAT(a.fecha, '%Y%m%d')fecha,'0002',
			IF(condi1='',CONCAT('ANTICIPO DE PROVEEDOR CREADO ',a.serie,'-',a.numero),CONCAT('ANTICIPO ',a.condi1)) as descrip, 'D',
			if(a.moneda='01',LPAD(ROUND(a.monto,2),16,0),LPAD(ROUND(a.monto*a.cambio,2),16,0)) monto,
			'G'as doc_cruce,a.serie serie_cruce,a.numero num_cruce,'001' sec_cruce,  
			INSERT(LPAD(a.cambio,12,0), 13,13, '0000') cambio,
			IF(a.moneda='01',LPAD(ROUND(a.monto/a.cambio,2),16,0),
			LPAD(a.monto,16,0)) montoe,
			RIGHT (formap,3) cod_formap,a.fecha,DATE_FORMAT(a.fecha, '%Y%m%d'),'0000',LPAD(a.referen,11,'0')referen	
			FROM itppro   AS a
			WHERE a.id='$items->id'";
			
			$this->db->query($G_c);
			
			$G_d="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp, ccomp,  ncomp,  secuencia,  nit, cuenta,  
			fdocu,  ccost,  descrip,  dc,  monto,cambio,  monto_me,  cod_mpago, fecha,fven_cruce,cvend,cheque)	
			SELECT a.id,'itppro' as tabla,a.moneda,'G',a.serie,a.numero,'00002'AS secu,LPAD(rif,13,0) ruc,a.cuenta,
			DATE_FORMAT(a.fecha, '%Y%m%d')fecha,'0002',
			a.condi1 as descrip, 'C',
			if(a.moneda='01',LPAD(ROUND(a.monto,2),16,0),LPAD(ROUND(a.monto*a.cambio,2),16,0)) monto,  
			INSERT(LPAD(a.cambio,12,0), 13,13, '0000') cambio,
			IF(a.moneda='01',LPAD(ROUND(a.monto/a.cambio,2),16,0),
			LPAD(a.monto,16,0)) montoe,
			RIGHT (formap,3) cod_formap,a.fecha,DATE_FORMAT(a.fecha, '%Y%m%d'),'0000',LPAD(a.referen,11,'0')referen	
			FROM itppro   AS a
			WHERE a.id='$items->id'";
			
			$this->db->query($G_d);
			
		}  
    }
    function _f($fechai,$fechaf){
        
        $items_fc=$this->cuenta->items_fc();
        $iva=$this->cuenta->iva();
		$igv=$this->datasis->traevalor('IGV');
        
        $this->db->query("DELETE FROM comprobantes WHERE tcomp IN ('F','B') AND fecha BETWEEN '$fechai' AND '$fechaf' AND tabla<>'siigo'");
        
        //****************************************************
		//Facturas de Venta
		
		$query=$this->db->query("SELECT id FROM sfac WHERE fecha BETWEEN '$fechai' AND '$fechaf'AND tipo_doc='FC' AND serie<>'101'");
		
		foreach($query->result() as $items ){
			
		$query_2=$this->db->query("SELECT id_spre FROM sitems WHERE id='$items->id'");
		$cant=$this->datasis->dameval("SELECT COUNT(*) FROM sitems WHERE id='$items->id'");
		
		$m1=$cant+1;
		$m2=$cant+2;
		
		$m1=STR_PAD($m1,5,0, STR_PAD_LEFT);	
		$m2=STR_PAD($m2,5,0, STR_PAD_LEFT);
		
		$F_d_cc="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
		fdocu,  ccost, descrip,  dc,cciud,  monto,    
		cambio,  monto_me, tdoc_cruce,ccomp_cruce,num_cruce,sec_cruce,fven_cruce,formap, fecha)
		SELECT a.id,'sfac' as tabla,moneda,IF(a.serie=100,'B','F') AS tcomp,'001' serie,a.numero,'$m1'AS secu,LPAD(rifci,13,0) ruc,cuenta,
		DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto,
		CONCAT('CUENTA POR COBRAR ',a.serie,'-',a.numero) descrip,'D','0013',
		if(a.moneda='01',LPAD(ROUND(a.totalg,2),16,0),LPAD(ROUND(a.totalg*cambio,2),16,0)) monto,
		INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(a.moneda='01',LPAD(ROUND(a.totalg/a.cambio,2),16,0),
		LPAD(a.totalg,16,0)) montoe,IF(a.serie=100,'B','F'),'001' AS serie,numero,'001',DATE_FORMAT(vence, '%Y%m%d')vence,
		LPAD(formap,4,0) cod_formap,fecha	
		FROM sfac AS a WHERE tipo_doc='FC'
		AND id='$items->id'";
				
		$this->db->query($F_d_cc);	
				
		$F_c_iva="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
		fdocu,  ccost, descrip,  dc,  monto,    
		cambio,  monto_me,fecha)			
		SELECT a.id,'sfac' as tabla,moneda,IF(a.serie=100,'B','F') AS tcomp,'001' serie,a.numero,'$m2'AS secu,LPAD(rifci,13,0) ruc,$iva,
		DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto,
		CONCAT('IVA DEL DOCUMENTO ',a.serie,'-',a.numero) descrip,'C',
		if(a.moneda='01',LPAD(ROUND(a.iva,2),16,0),LPAD(ROUND(a.iva*cambio,2),16,0)) monto,
		INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(a.moneda='01',LPAD(ROUND(a.iva/a.cambio,2),16,0),LPAD(a.iva,16,0)) montoe,fecha	
		FROM sfac AS a WHERE tipo_doc='FC'
		AND id='$items->id'";
		
		$this->db->query($F_c_iva);
		
		$i=1;	
						
		foreach($query_2->result() as $detalle ){
		
		$ii =STR_PAD($i,5,0, STR_PAD_LEFT);
		$j  =STR_PAD($i,3,0, STR_PAD_LEFT);
			
				$F_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
				fdocu,  ccost, cprod,descrip,cant,  dc,cciud,cbode, monto,cambio,  monto_me,fecha,piva,puni_ml,puni_me,
				met_depre,pcargo,cant2,ind_tmovi,viva,tdoc_pedido,ccom_pedido,num_pedido,sec_pedido)	
				SELECT a.id,'sfac' as tabla,b.moneda,IF(b.serie=100,'B','F') AS tcomp,'001'serie,a.numero,'$ii'AS secu,LPAD(rifci,13,0) ruc,'$items_fc',
				DATE_FORMAT(fecha, '%Y%m%d')fecha,'0002'ccosto, csiigo,a.descrip,
				INSERT(LPAD(IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,f.cantidad),13,0), 14,14, '000')cantidad,'C',
				'0013'ciudad,almacen,
				if(b.moneda='01',LPAD(ROUND(IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,f.cantidad)*(a.total/a.cantidad),2),16,0),LPAD(ROUND(IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,f.cantidad)*(a.total/a.cantidad)*cambio,2),16,0)) monto,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,				
				IF(b.moneda='01',LPAD(ROUND((IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,f.cantidad)*(a.total/a.cantidad))/cambio,2),16,0),
				LPAD(round(IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,f.cantidad)*(a.total/a.cantidad),2),16,0)) montoe,	
				fecha,RPAD('$igv',4,0),
				if(b.moneda='01',LPAD(ROUND((IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,f.cantidad)*(a.total/a.cantidad))/IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,f.cantidad))),5),19,0),LPAD(ROUND((IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,f.cantidad)*(a.total/a.cantidad))/IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,f.cantidad)*cambio,5),19,0)) puni_ml,
				if(b.moneda='02',LPAD(ROUND((IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,f.cantidad)*(a.total/a.cantidad))/IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,f.cantidad))),5),19,0),LPAD(ROUND((IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,f.cantidad)*(a.total/a.cantidad))/IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,f.cantidad)/cambio,5),19,0)) puni_me,
				'R',RPAD('$igv',4,0),INSERT(LPAD(IF(a.codigo IN ('FLETE','SEGURO','CORTINA'),a.cantidad,f.cantidad),16,0), 17,17, '000')cantidad2,'S',
				LPAD(ROUND((a.total*'$igv'/100),2),14,0) viva,'S','002',f.nguia,'$j' AS sec_pedido	
				FROM sitems AS a
				JOIN sfac AS b ON a.id=b.id AND b.tipo_doc='FC'
				JOIN sinv AS c ON a.codigo=c.codigo
				LEFT JOIN despachos AS f ON b.numero=f.factura and a.codigo=f.codigo and f.tipo_doc='FC' 
				WHERE id_spre='$detalle->id_spre'"; 
						
				$this->db->query($F_c_items);
				//falta campo piva
				//falta un campo que señala la cantidad
				//falta la relacion con las guias
				$i++;
			}
			
		}
        
        //******************************
        //ajustes de salida por boleta
        //******************************
        
        $this->db->query("DELETE FROM comprobantes WHERE tcomp='f'  AND ccomp  IN ('101') AND fecha BETWEEN '$fechai' AND '$fechaf' AND tabla<>'siigo'");
        		
		$query=$this->db->query("SELECT id FROM sfac WHERE fecha BETWEEN '$fechai' AND '$fechaf'AND tipo_doc='FC' AND serie='101'");
		
		foreach($query->result() as $items ){
			
		$query_2=$this->db->query("SELECT id_spre FROM sitems WHERE id='$items->id'");
		$cant=$this->datasis->dameval("SELECT COUNT(*) FROM sitems WHERE id='$items->id'");
		
		$m1=$cant*3+1;
		$m2=$cant*3+2;
		$m3=$cant*3+3;
		$m4=$cant*3+4;
		
		$m1=STR_PAD($m1,5,0, STR_PAD_LEFT);	
		$m2=STR_PAD($m2,5,0, STR_PAD_LEFT);
		$m3=STR_PAD($m3,5,0, STR_PAD_LEFT);
		$m4=STR_PAD($m4,5,0, STR_PAD_LEFT);
		
		$F_d_cc="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
		fdocu,  ccost, descrip,  dc,cciud,  monto,    
		cambio,  monto_me, tdoc_cruce,ccomp_cruce,num_cruce,sec_cruce,fven_cruce,formap, fecha)
		SELECT a.id,'sfac' as tabla,moneda,'B','001' serie,a.numero,'$m1'AS secu,LPAD(rifci,13,0) ruc,'7901010000'cuenta,
		DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto,
		CONCAT('CUENTA POR COBRAR ','B001-',a.numero) descrip,'C','0013',
		if(a.moneda='01',LPAD(ROUND(a.totalg,2),16,0),LPAD(ROUND(a.totalg*cambio,2),16,0)) monto,
		INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(a.moneda='01',LPAD(ROUND(a.totalg/a.cambio,2),16,0),
		LPAD(a.totalg,16,0)) montoe,'F',serie,numero,'001',DATE_FORMAT(vence, '%Y%m%d')vence,
		LPAD(formap,4,0) cod_formap,fecha	
		FROM sfac AS a WHERE tipo_doc='FC'
		AND id='$items->id'";
				
		$this->db->query($F_d_cc);	
				
		$F_c_iva="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
		fdocu,  ccost, descrip,  dc,  monto,    
		cambio,  monto_me,fecha)			
		SELECT a.id,'sfac' as tabla,moneda,'B','001' serie,a.numero,'$m2'AS secu,LPAD(rifci,13,0) ruc,'9464010100' cuenta,
		DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto,
		CONCAT('BOLETA DE SALIDA ','B001-',a.numero) descrip,'D',
		if(a.moneda='01',LPAD(ROUND(a.iva,2),16,0),LPAD(ROUND(a.iva*cambio,2),16,0)) monto,
		INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(a.moneda='01',LPAD(ROUND(a.iva/a.cambio,2),16,0),LPAD(a.iva,16,0)) montoe,fecha	
		FROM sfac AS a WHERE tipo_doc='FC'
		AND id='$items->id'";
		
		$this->db->query($F_c_iva);
		
		$F_c_iva1="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
		fdocu,  ccost, descrip,  dc,  monto,    
		cambio,  monto_me,fecha)			
		SELECT a.id,'sfac' as tabla,moneda,'B','001' serie,a.numero,'$m3'AS secu,LPAD(rifci,13,0) ruc,'4001010100' cuenta,
		DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto,
		CONCAT('BOLETA DE SALIDA ','B001-',a.numero) descrip,'C',
		if(a.moneda='01',LPAD(ROUND(a.iva,2),16,0),LPAD(ROUND(a.iva*cambio,2),16,0)) monto,
		INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(a.moneda='01',LPAD(ROUND(a.iva/a.cambio,2),16,0),LPAD(a.iva,16,0)) montoe,fecha	
		FROM sfac AS a WHERE tipo_doc='FC'
		AND id='$items->id'";
		
		$this->db->query($F_c_iva1);
		
		$F_c_iva2="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
		fdocu,  ccost, descrip,  dc,  monto,    
		cambio,  monto_me,fecha)			
		SELECT a.id,'sfac' as tabla,moneda,'B','001' serie,a.numero,'$m4'AS secu,LPAD(rifci,13,0) ruc,'6401010000' cuenta,
		DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto,
		CONCAT('BOLETA DE SALIDA ','B001-',a.numero) descrip,'D',
		if(a.moneda='01',LPAD(ROUND(a.iva,2),16,0),LPAD(ROUND(a.iva*cambio,2),16,0)) monto,
		INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(a.moneda='01',LPAD(ROUND(a.iva/a.cambio,2),16,0),LPAD(a.iva,16,0)) montoe,fecha	
		FROM sfac AS a WHERE tipo_doc='FC'
		AND id='$items->id'";
		
		$this->db->query($F_c_iva2);
		
		$i=1;	
						
		foreach($query_2->result() as $detalle ){
		
		$ii =STR_PAD($i,5,0, STR_PAD_LEFT);
		$j  =STR_PAD($i,3,0, STR_PAD_LEFT);
			
				$F_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
				fdocu,  ccost, cprod,descrip,cant,  dc,cciud,cbode, monto,cambio,  monto_me,fecha,piva,puni_ml,puni_me,
				met_depre,pcargo,cant2,ind_tmovi,viva,tdoc_pedido,ccom_pedido,num_pedido,sec_pedido)	
				SELECT a.id,'sfac' as tabla,b.moneda,'B','001' serie,a.numero,'$ii'AS secu,LPAD(rifci,13,0) ruc,'2001010100',
				DATE_FORMAT(fecha, '%Y%m%d')fecha,'0002'ccosto, csiigo,a.descrip,
				INSERT(LPAD(f.cantidad,13,0), 14,14, '000')cantidad,'C',
				'0013'ciudad,almacen,
				if(b.moneda='01',LPAD(ROUND(f.cantidad*(a.total/a.cantidad),2),16,0),LPAD(ROUND(f.cantidad*(a.total/a.cantidad)*cambio,2),16,0)) monto,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,				
				IF(b.moneda='01',LPAD(ROUND((f.cantidad*(a.total/a.cantidad))/cambio,2),16,0),
				LPAD(round(f.cantidad*(a.total/a.cantidad),2),16,0)) montoe,	
				fecha,RPAD('$igv',4,0),
				if(b.moneda='01',LPAD(ROUND((f.cantidad*(a.total/a.cantidad))/f.cantidad,5),19,0),LPAD(ROUND((f.cantidad*(a.total/a.cantidad))/f.cantidad*cambio,5),19,0)) puni_ml,
				if(b.moneda='02',LPAD(ROUND((f.cantidad*(a.total/a.cantidad))/f.cantidad,5),19,0),LPAD(ROUND((f.cantidad*(a.total/a.cantidad))/f.cantidad/cambio,5),19,0)) puni_me,
				'R',RPAD('$igv',4,0),INSERT(LPAD(f.cantidad,16,0), 17,17, '000')cantidad2,'S',
				LPAD(ROUND((a.total*'$igv'/100),2),14,0) viva,'S','002',f.nguia,'$j' AS sec_pedido	
				FROM sitems AS a
				JOIN sfac AS b ON a.id=b.id AND b.tipo_doc='FC'
				JOIN sinv AS c ON a.codigo=c.codigo
				LEFT JOIN despachos AS f ON b.numero=f.factura and a.codigo=f.codigo and f.tipo_doc='FC' 
				WHERE id_spre='$detalle->id_spre'"; 
						
				$this->db->query($F_c_items);
				$i++;
			}
			
			foreach($query_2->result() as $detalle2 ){
		
			$ii =STR_PAD($i,5,0, STR_PAD_LEFT);
			$j  =STR_PAD($i,3,0, STR_PAD_LEFT);
			
				$F_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
				fdocu,  ccost, cprod,descrip,cant,  dc,cciud,cbode, monto,cambio,  monto_me,fecha,piva,puni_ml,puni_me,
				met_depre,pcargo,cant2,ind_tmovi,viva,tdoc_pedido,ccom_pedido,num_pedido,sec_pedido)	
				SELECT a.id,'sfac' as tabla,b.moneda,'B','001' serie,a.numero,'$ii'AS secu,LPAD(rifci,13,0) ruc,'9565090500',
				DATE_FORMAT(fecha, '%Y%m%d')fecha,'0002'ccosto, csiigo,a.descrip,
				INSERT(LPAD(f.cantidad,13,0), 14,14, '000')cantidad,'D',
				'0013'ciudad,almacen,
				if(b.moneda='01',LPAD(ROUND(f.cantidad*(a.total/a.cantidad),2),16,0),LPAD(ROUND(f.cantidad*(a.total/a.cantidad)*cambio,2),16,0)) monto,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,				
				IF(b.moneda='01',LPAD(ROUND((f.cantidad*(a.total/a.cantidad))/cambio,2),16,0),
				LPAD(round(f.cantidad*(a.total/a.cantidad),2),16,0)) montoe,	
				fecha,RPAD('$igv',4,0),
				if(b.moneda='01',LPAD(ROUND((f.cantidad*(a.total/a.cantidad))/f.cantidad,5),19,0),LPAD(ROUND((f.cantidad*(a.total/a.cantidad))/f.cantidad*cambio,5),19,0)) puni_ml,
				if(b.moneda='02',LPAD(ROUND((f.cantidad*(a.total/a.cantidad))/f.cantidad,5),19,0),LPAD(ROUND((f.cantidad*(a.total/a.cantidad))/f.cantidad/cambio,5),19,0)) puni_me,
				'R',RPAD('$igv',4,0),INSERT(LPAD(f.cantidad,16,0), 17,17, '000')cantidad2,'S',
				LPAD(ROUND((a.total*'$igv'/100),2),14,0) viva,'S','002',f.nguia,'$j' AS sec_pedido	
				FROM sitems AS a
				JOIN sfac AS b ON a.id=b.id AND b.tipo_doc='FC'
				JOIN sinv AS c ON a.codigo=c.codigo
				LEFT JOIN despachos AS f ON b.numero=f.factura and a.codigo=f.codigo and f.tipo_doc='FC' 
				WHERE id_spre='$detalle2->id_spre'"; 
						
				$this->db->query($F_c_items);
				$i++;
			}
			
			foreach($query_2->result() as $detalle3 ){
		
			$ii =STR_PAD($i,5,0, STR_PAD_LEFT);
			$j  =STR_PAD($i,3,0, STR_PAD_LEFT);
			
				$F_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
				fdocu,  ccost, cprod,descrip,cant,  dc,cciud,cbode, monto,cambio,  monto_me,fecha,piva,puni_ml,puni_me,
				met_depre,pcargo,cant2,ind_tmovi,viva,tdoc_pedido,ccom_pedido,num_pedido,sec_pedido)	
				SELECT a.id,'sfac' as tabla,b.moneda,'B','001' serie,a.numero,'$ii'AS secu,LPAD(rifci,13,0) ruc,'6509050000',
				DATE_FORMAT(fecha, '%Y%m%d')fecha,'0002'ccosto, csiigo,a.descrip,
				INSERT(LPAD(f.cantidad,13,0), 14,14, '000')cantidad,'D',
				'0013'ciudad,almacen,
				if(b.moneda='01',LPAD(ROUND(f.cantidad*(a.total/a.cantidad),2),16,0),LPAD(ROUND(f.cantidad*(a.total/a.cantidad)*cambio,2),16,0)) monto,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,				
				IF(b.moneda='01',LPAD(ROUND((f.cantidad*(a.total/a.cantidad))/cambio,2),16,0),
				LPAD(round(f.cantidad*(a.total/a.cantidad),2),16,0)) montoe,	
				fecha,RPAD('$igv',4,0),
				if(b.moneda='01',LPAD(ROUND((f.cantidad*(a.total/a.cantidad))/f.cantidad,5),19,0),LPAD(ROUND((f.cantidad*(a.total/a.cantidad))/f.cantidad*cambio,5),19,0)) puni_ml,
				if(b.moneda='02',LPAD(ROUND((f.cantidad*(a.total/a.cantidad))/f.cantidad,5),19,0),LPAD(ROUND((f.cantidad*(a.total/a.cantidad))/f.cantidad/cambio,5),19,0)) puni_me,
				'R',RPAD('$igv',4,0),INSERT(LPAD(f.cantidad,16,0), 17,17, '000')cantidad2,'S',
				LPAD(ROUND((a.total*'$igv'/100),2),14,0) viva,'S','002',f.nguia,'$j' AS sec_pedido	
				FROM sitems AS a
				JOIN sfac AS b ON a.id=b.id AND b.tipo_doc='FC'
				JOIN sinv AS c ON a.codigo=c.codigo
				LEFT JOIN despachos AS f ON b.numero=f.factura and a.codigo=f.codigo and f.tipo_doc='FC' 
				WHERE id_spre='$detalle3->id_spre'"; 
						
				$this->db->query($F_c_items);
				$i++;
			}
			
		}
        
    }
    function _s($fechai,$fechaf){
        
        $this->db->query("DELETE FROM comprobantes WHERE tcomp='S' AND fecha BETWEEN '$fechai' AND '$fechaf' AND tabla<>'siigo'");
        
        //**********************************
		//Guias de Remisiòn

		$query=$this->db->query("SELECT id FROM remision WHERE fecha BETWEEN '$fechai' AND '$fechaf'");

		foreach($query->result() as $items ){
		
		$query_2=$this->db->query("SELECT id,remision FROM despachos WHERE remision='$items->id'");
		
		$i=1;
		
		foreach($query_2->result() as $detalle ){
		
		$sec1=STR_PAD($i,5,0, STR_PAD_LEFT);
		
		//echo $secu1." ".$detalle->remision.'</br>';
			
				$guia="INSERT INTO comprobantes (id,tabla,tcomp,  ccomp,  ncomp, fdocu,cprod,descrip,cant,
				cuenta, ccost, dc, cciud,cbode, secuencia,  nit,  
				cambio,
				ncom_prov,ndoc_prov,fdoc_prov,fecha,cant2,doc_banco)	
				SELECT a.id,'remision' as tabla,'S','002',a.nguia,DATE_FORMAT(fecha, '%Y%m%d')fecha,c.csiigo,LEFT(c.descrip,50),
				INSERT(LPAD(b.cantidad,13,0), 14,14, '000')cantidad,
				'2001010100'cuenta,'0002'ccosto,'C' as dc,'0013' as cciud,'0001' as almacen,'$sec1' as secu,LPAD(rucd,13,0) ruc,
				INSERT(LPAD((SELECT cambio FROM cambio as e WHERE a.fecha=e.fecha),12,0), 13,13, '0000') cambio,
				'0001',	a.nguia,DATE_FORMAT(fecha, '%Y%m%d')fecha,fecha,
				INSERT(LPAD(b.cantidad,16,0), 17,17, '000')cantidad2,LPAD(a.nguia,12,0)	
				FROM despachos AS b
				JOIN sinv AS c on b.codigo=c.codigo
				JOIN remision AS a  ON b.remision=a.id		
				WHERE b.id='$detalle->id' and a.tipo_doc='FC' "; 
				
				//echo ''.$guia.' '.$detalle->remision.''.$sec1.'</br>';
						
				$this->db->query($guia);
				//falta un campo que señala la cantidad
				//falta precios
				$i++;
			}
		}
    }
    function _cni($fechai,$fechaf){
        
        $iva=$this->cuenta->iva();
		$igv=$this->datasis->traevalor('IGV');
        
        //$this->db->query("DELETE FROM comprobantes WHERE tcomp='L' and ccomp='005' AND fecha BETWEEN '$fechai' AND '$fechaf'");
        $this->db->query("DELETE FROM comprobantes WHERE tcomp IN ('P','L') and ccomp IN ('008','005') AND fecha BETWEEN '$fechai' AND '$fechaf' AND tabla<>'siigo'");
         
        //****************************************************
		//Facturas de Compras
		
		$query=$this->db->query("SELECT control,seriei FROM scst WHERE comp IN ('P','L') and seriei IN ('008','005') AND recep BETWEEN '$fechai' AND '$fechaf'");
		
		foreach($query->result() as $items ){
			
		$query_2=$this->db->query("SELECT id FROM itscst WHERE control='$items->control'");
		$cant   =$this->datasis->dameval("SELECT COUNT(*) FROM itscst WHERE control='$items->control'");
		$viva    =$this->datasis->dameval("SELECT montoiva FROM scst WHERE control='$items->control'");
		$items_p=$this->cuenta->items_p($items->seriei);
		
		IF($viva>0){
			$vigv=$igv;
			$ind_tmovi='S';
			$coa='S';
			
		}else{
			
			$vigv=0;
			$ind_tmovi='N';
			$coa='N';
			
		}
        
        $P_c_cp="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,  cuenta,tdoc_cruce,ccomp_cruce,num_cruce,sec_cruce,
		fven_cruce,fdocu,  ccost, 
		descrip,  dc,  monto,  cvend, cambio,  monto_me,
		fecha,formap,ncom_prov,ndoc_prov,fdoc_prov,cpago)
		SELECT a.control,'scst' as tabla,moneda,IF(seriei='005','L','P') tcomp,a.seriei,a.numeroi,'00001'AS secu,LPAD(rifci,13,0) ruc,'000'sucu,IF(seriei='005','2801011100',cuenta)cuenta,'P',a.seriep,a.numero,'001'secu,
		DATE_FORMAT(a.vence, '%Y%m%d')vence,DATE_FORMAT(a.recep, '%Y%m%d')fecha,ccosto, 
        IF(seriei='005',CONCAT('TOTAL DE GASTO POR IMPORTACION ',numeroi),CONCAT('CUENTA POR PAGAR ',seriep,'-',numero)) descrip,'C',
		if(a.moneda='01',LPAD(ROUND(a.montonet,2),16,0),LPAD(ROUND(a.montonet*cambio,2),16,0)) monto,
		'0000'vd,INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(moneda='02',LPAD(ROUND(a.montonet,2),16,0),LPAD(a.montonet/cambio,16,0)) montoe,
		a.recep,LPAD(formap,4,0),LPAD(a.seriep,4,0),a.numero,DATE_FORMAT(a.recep, '%Y%m%d')fecha,a.numero	
		FROM scst AS a
		WHERE control='$items->control'";
				
		$this->db->query($P_c_cp);
		
		IF($viva>0){
		
			$P_c_iva="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,  cuenta,tdoc_cruce,ccomp_cruce,num_cruce,sec_cruce,fven_cruce,
			fdocu,  ccost, descrip,  dc,  monto,  cvend, cambio,  monto_me,fecha,formap,ncom_prov,ndoc_prov,fdoc_prov,cpago)
			SELECT a.control,'scst' as tabla,moneda,IF(seriei='005','L','P') tcomp,a.seriei,a.numeroi,'00002'AS secu,LPAD(rifci,13,0) ruc,'000'sucu,'$iva','P',a.seriep,a.numero,'001'secu,
			DATE_FORMAT(a.vence, '%Y%m%d')vence,DATE_FORMAT(a.recep, '%Y%m%d')fecha,ccosto, 
			CONCAT('IVA DEL DOCUMENTO ',seriep,'-',numero)descrip,'D',
			if(a.moneda='01',LPAD(ROUND(a.montoiva,2),16,0),LPAD(ROUND(a.montoiva*cambio,2),16,0)) monto,
			'0000'vd,INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			IF(moneda='02',LPAD(ROUND(a.montoiva,2),16,0),LPAD(a.montoiva/cambio,16,0)) montoe,
			a.recep,LPAD(formap,4,0),LPAD(a.seriep,4,0),a.numero,DATE_FORMAT(a.recep, '%Y%m%d')fecha,a.numero	
			FROM scst AS a
			WHERE control='$items->control'";
			
			$this->db->query($P_c_iva);
		
		}
		
		IF($viva>0){$i=3;}else{$i=2;}
        						
		foreach($query_2->result() as $detalle ){
		
			$a=$i+1;
            $b=$i+2;
            
            $i=STR_PAD($i,5,0, STR_PAD_LEFT);
            $a=STR_PAD($a,5,0, STR_PAD_LEFT);
            $b=STR_PAD($b,5,0, STR_PAD_LEFT);
				
			$P_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,  cuenta,  
			fdocu,  ccost, descrip,cprod,dc,  monto, cant, cvend,cbode,
			cambio,  monto_me, fecha,ind_tmovi,piva,viva,ncom_prov,ndoc_prov,fdoc_prov,cpago,met_depre,pcargo,fven_cruce,cant2,puni_ml,puni_me)
			SELECT a.control,'scst' as tabla,b.moneda,IF(seriei='005','L','P') tcomp,b.seriei,b.numeroi,'$i'AS secu,LPAD(rifci,13,0) ruc,'000'sucu,'$items_p' cuenta,
			DATE_FORMAT(b.recep, '%Y%m%d')fecha,ccosto,c.descrip,csiigo,'D',
			if(b.moneda='01',LPAD(ROUND(a.importe,2),16,0),LPAD(ROUND(a.importe*cambio,2),16,0)) monto, 
			INSERT(LPAD(a.cantidad,14,0), 15,15, '00')cantidad,'0000'vd,b.depo,
			INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			IF(b.moneda='02',LPAD(ROUND(a.importe,2),16,0),LPAD(ROUND(a.importe/cambio,2),16,0)) montoe,
			b.recep,'$ind_tmovi',RPAD($vigv,4,0) as piva,LPAD(ROUND((a.costo*$vigv/100),2),14,0) viva,
			LPAD(b.seriep,4,0),b.numero,DATE_FORMAT(b.recep, '%Y%m%d')fecha,b.numero,'$coa',RPAD('$vigv',4,0) as pcargo,DATE_FORMAT(b.vence, '%Y%m%d')vence,
			INSERT(LPAD(a.cantidad,17,0), 18,18, '00')cantidad,
			if(b.moneda='01',LPAD(ROUND(a.costo,5),19,0),LPAD(ROUND(a.costo*cambio,5),19,0)) puni_ml,
			if(b.moneda='02',LPAD(ROUND(a.costo,5),19,0),LPAD(ROUND(a.costo/cambio,5),19,0)) puni_me	
			FROM itscst AS a
			JOIN scst AS b ON a.control=b.control
			JOIN sinv AS c ON a.codigo=c.codigo
			WHERE a.id='$detalle->id'";
			
			$this->db->query($P_c_items);
            
            $P_c_aju="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,  cuenta,  
			fdocu,  ccost, descrip,cprod,dc,  monto, cant, cvend,cbode,
			cambio,  monto_me, fecha,ind_tmovi,piva,viva,ncom_prov,ndoc_prov,fdoc_prov,cpago,met_depre,pcargo,fven_cruce,cant2,puni_ml,puni_me)
			SELECT a.control,'scst' as tabla,b.moneda,IF(seriei='005','L','P') tcomp,b.seriei,b.numeroi,'$a'AS secu,LPAD(rifci,13,0) ruc,'000'sucu,'6001010000' cuenta,
			DATE_FORMAT(b.recep, '%Y%m%d')fecha,ccosto,c.descrip,csiigo,'D',
			if(b.moneda='01',LPAD(ROUND(a.importe,2),16,0),LPAD(ROUND(a.importe*cambio,2),16,0)) monto, 
			INSERT(LPAD(a.cantidad,14,0), 15,15, '00')cantidad,'0000'vd,b.depo,
			INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			IF(b.moneda='02',LPAD(ROUND(a.importe,2),16,0),LPAD(ROUND(a.importe/cambio,2),16,0)) montoe,
			b.recep,'$ind_tmovi',RPAD($vigv,4,0) as piva,LPAD(ROUND((a.costo*$vigv/100),2),14,0) viva,
			LPAD(b.seriep,4,0),b.numero,DATE_FORMAT(b.recep, '%Y%m%d')fecha,b.numero,'$coa',RPAD('$vigv',4,0) as pcargo,DATE_FORMAT(b.vence, '%Y%m%d')vence,
			INSERT(LPAD(a.cantidad,17,0), 18,18, '00')cantidad,
			if(b.moneda='01',LPAD(ROUND(a.costo,5),19,0),LPAD(ROUND(a.costo*cambio,5),19,0)) puni_ml,
			if(b.moneda='02',LPAD(ROUND(a.costo,5),19,0),LPAD(ROUND(a.costo/cambio,5),19,0)) puni_me	
			FROM itscst AS a
			JOIN scst AS b ON a.control=b.control
			JOIN sinv AS c ON a.codigo=c.codigo
			WHERE a.id='$detalle->id'";
            
            $this->db->query($P_c_aju);
            
            $P_c_cont="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,  cuenta,  
			fdocu,  ccost, descrip,cprod,dc,  monto, cant, cvend,cbode,
			cambio,  monto_me, fecha,ind_tmovi,piva,viva,ncom_prov,ndoc_prov,fdoc_prov,cpago,met_depre,pcargo,fven_cruce,cant2,puni_ml,puni_me)
			SELECT a.control,'scst' as tabla,b.moneda,IF(seriei='005','L','P') tcomp,b.seriei,b.numeroi,'$b'AS secu,LPAD(rifci,13,0) ruc,'000'sucu,'6101010000' cuenta,
			DATE_FORMAT(b.recep, '%Y%m%d')fecha,ccosto,c.descrip,csiigo,'C',
			if(b.moneda='01',LPAD(ROUND(a.importe,2),16,0),LPAD(ROUND(a.importe*cambio,2),16,0)) monto, 
			INSERT(LPAD(a.cantidad,14,0), 15,15, '00')cantidad,'0000'vd,b.depo,
			INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			IF(b.moneda='02',LPAD(ROUND(a.importe,2),16,0),LPAD(ROUND(a.importe/cambio,2),16,0)) montoe,
			b.recep,'$ind_tmovi',RPAD($vigv,4,0) as piva,LPAD(ROUND((a.costo*$vigv/100),2),14,0) viva,
			LPAD(b.seriep,4,0),b.numero,DATE_FORMAT(b.recep, '%Y%m%d')fecha,b.numero,'$coa',RPAD('$vigv',4,0) as pcargo,DATE_FORMAT(b.vence, '%Y%m%d')vence,
			INSERT(LPAD(a.cantidad,17,0), 18,18, '00')cantidad,
			if(b.moneda='01',LPAD(ROUND(a.costo,5),19,0),LPAD(ROUND(a.costo*cambio,5),19,0)) puni_ml,
			if(b.moneda='02',LPAD(ROUND(a.costo,5),19,0),LPAD(ROUND(a.costo/cambio,5),19,0)) puni_me	
			FROM itscst AS a
			JOIN scst AS b ON a.control=b.control
			JOIN sinv AS c ON a.codigo=c.codigo
			WHERE a.id='$detalle->id'";
            
            $this->db->query($P_c_cont);
		
			$i++;
            }		
	
        }    
        
        
        
    }
    function _l($fechai,$fechaf){
        
        $iva=$this->cuenta->iva();
		$igv=$this->datasis->traevalor('IGV');
        
        $this->db->query("DELETE FROM comprobantes WHERE tcomp='L'  AND ccomp NOT IN ('006','007','005') AND fecha BETWEEN '$fechai' AND '$fechaf' AND tabla<>'siigo'");
        
		//************************
		//L010 por redondeo y diferencia de cambio
		//***********************
				
		$query=$this->db->query("SELECT a.id,a.moneda,a.tipo FROM itppro as a
		JOIN bancos as b on a.serie=b.codigo WHERE b.tipo='O' AND fecha BETWEEN '$fechai' AND '$fechaf'");
		
		foreach($query->result() as $items ){
			
		$query_2=$this->db->query("SELECT id FROM relacion WHERE itppro='$items->id' AND tipod='L'");
		$query_3=$this->db->query("SELECT idt FROM itpprot  WHERE id='$items->id'");
		
		
		$secu2=$query_2->num_rows();
		$secu2=$secu2+1;
		$secu2=STR_PAD($secu2,5,0,STR_PAD_LEFT);
        				
		$G_d="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
		fdocu,  ccost,  descrip,  dc,  monto, 
		cambio,  monto_me, cod_mpago, fecha,cheque,cvend)	
		SELECT a.id,'itppro' as tabla, moneda,'L','010'serie,numero,'00001'AS secu,LPAD(rif,13,0) ruc,cuenta,
		DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto, 
		a.condi1 as descrip,'D',
		if(a.moneda='01',LPAD(ROUND(a.monto,2),16,0),LPAD(ROUND(a.monto*a.cambio,2),16,0)) monto,
		INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(a.moneda='01',LPAD(ROUND(a.monto/a.cambio,2),16,0),LPAD(a.monto,16,0)) montoe,
		RIGHT (formap,3) cod_formap,fecha,LPAD(a.referen,11,'0')referen,'0000'	
		FROM itppro AS a	
		WHERE a.id='$items->id'";
		
		$this->db->query($G_d);
		
		$i=2;
						
		foreach($query_2->result() as $detalle ){
			
		$secu1=STR_PAD($i,5,0, STR_PAD_LEFT);
		$ii   =STR_PAD($i,3,0, STR_PAD_LEFT);
		
        
            $G_c="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp, ccomp,  ncomp,  secuencia,  nit, cuenta,  
				fdocu,  ccost,  descrip,  dc,  monto,tdoc_cruce, 
				ccomp_cruce,  num_cruce,  sec_cruce, cambio,  monto_me,  cod_mpago, fecha,fven_cruce,cvend,cheque)	
				SELECT a.id,'itppro' as tabla,a.moneda,'L','010' serie,a.numero,'$secu1'AS secu,LPAD(rif,13,0) ruc,
				if((SELECT cuenta FROM gser as g WHERE c.transac=g.transac)IS NULL,(SELECT cuenta FROM scst as g WHERE c.transac=g.transac),(SELECT cuenta FROM gser as g WHERE c.transac=g.transac))cuenta,
				DATE_FORMAT(a.fecha, '%Y%m%d')fecha,'0002',RPAD(CONCAT('DOCUMENTO ',b.serief,'-',b.factura),50,' ')as descrip,'C',
				IF(a.moneda='01',LPAD(ROUND(b.monto,2),16,0),LPAD(ROUND(b.monto*a.cambio,2),16,0))monto,				
                'P'as doc_cruce,serief as serie_cruce,b.factura num_cruce,'$ii' sec_cruce,  
                INSERT(LPAD(a.cambio,12,0), 13,13, '0000') cambio,
				IF(a.moneda='01',LPAD(ROUND(b.monto/a.cambio,2),16,0),LPAD(b.monto,16,0))montoe,
				RIGHT (formap,3) cod_formap,a.fecha,DATE_FORMAT(c.vence, '%Y%m%d'),'0000',LPAD(a.referen,11,'0')referen	
				FROM itppro   AS a
				JOIN relacion AS b ON a.id=b.itppro
				JOIN sprm     AS c ON b.serief=c.seriep  AND b.factura=c.numero AND b.cod_prv=c.cod_prv
				WHERE b.id='$detalle->id'";
            		
				
				$this->db->query($G_c);
				
				$i++;
			}
			
			foreach($query_3->result() as $detalle ){
				
			$secu2=STR_PAD($i,5,0, STR_PAD_LEFT);
			$ii   =STR_PAD($i,3,0, STR_PAD_LEFT);
						
									
				$G_o="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
				fdocu,  ccost,  descrip,  dc,  monto, 
				cambio,  monto_me, cod_mpago, fecha,cheque,cvend)
				SELECT a.id,'itpprot' as tabla, moneda,'L','010' serie,numero,'$secu2'AS secu,LPAD(trim(b.ruc),13,0) ruc,b.cuenta,
				DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto, 
				b.desca as descrip,'C' tipo,
				if(a.moneda='01',LPAD(ROUND(b.importe,2),16,0),LPAD(ROUND(b.importe*a.cambio,2),16,0)) monto,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
				IF(a.moneda='01',LPAD(ROUND(b.importe/a.cambio,2),16,0),LPAD(b.importe,16,0)) montoe,
				RIGHT (formap,3) cod_formap,fecha,LPAD(a.referen,11,'0')referen,'0000'	
				FROM itppro AS a
				JOIN itpprot as b on a.id=b.id
				WHERE b.idt='$detalle->idt'";
				
				$this->db->query($G_o);
					
				$i++;
				
			}
		}
		
		
		//************************************
		//Ajustes de entrada
		//************************************
		
		$query_2=$this->db->query("SELECT numero FROM ssal WHERE tipo='E' AND fecha BETWEEN '$fechai' AND '$fechaf'  AND tipo_doc='FC'");
		
		foreach($query_2->result() as $items2 ){
			
			$query_3=$this->db->query("SELECT id FROM itssal WHERE numero='$items2->numero'");
			
			$i=1;
			foreach($query_3->result() as $items3 ){
				
				$i=STR_PAD($i,5,0, STR_PAD_LEFT);
				
				$l_d_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  cuenta,  
				fdocu,  ccost, cprod,descrip,  dc, cant, monto, cambio,  monto_me, fecha)
				SELECT b.id,'ssal' as tabla,b.moneda,'L' comp,'010'seriei,a.numero,'$i'AS secu,'2001010000'cuenta,
				DATE_FORMAT(b.fecha, '%Y%m%d')fecha,'0002' ccosto, 
				c.csiigo,CONCAT(c.descrip,' ',c.descrip2) as desca,'D',INSERT(LPAD(a.cantidad,13,0), 14,14, '000')cantidad,
				LPAD(round(a.costomn*a.cantidad,2),16,0) monto,
				INSERT(LPAD((SELECT cambio FROM cambio AS f WHERE f.fecha=b.fecha),12,0), 13,13, '0000') cambio,
				LPAD(round(a.costome*a.cantidad,2),16,0) montoe,
				b.fecha	
				FROM itssal AS a
				JOIN ssal AS b ON a.numero=b.numero
				JOIN sinv AS c on a.codigo=c.codigo
				WHERE a.id='$items3->id'
				GROUP BY a.id";
				
				$this->db->query($l_d_items);
	
				$i++;		
			}
			
			foreach($query_3->result() as $items4 ){
				
				$i=STR_PAD($i,5,0, STR_PAD_LEFT);
				
				$l_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  cuenta,  
				fdocu,  ccost, cprod,descrip, dc, cant,monto, cambio,  monto_me, fecha)
				SELECT b.id,'ssal' as tabla,b.moneda,'L' comp,'010'seriei,a.numero,'$i'AS secu,'7509050000'cuenta,
				DATE_FORMAT(b.fecha, '%Y%m%d')fecha,'0002' ccosto, 
				c.csiigo,CONCAT(c.descrip,' ',c.descrip2) as desca,'C',INSERT(LPAD(a.cantidad,13,0), 14,14, '000')cantidad,
				LPAD(round(a.costomn*a.cantidad,2),16,0) monto,
				INSERT(LPAD((SELECT cambio FROM cambio AS f WHERE f.fecha=b.fecha),12,0), 13,13, '0000') cambio,
				LPAD(round(a.costome*a.cantidad,2),16,0) montoe,
				b.fecha	
				FROM itssal AS a
				JOIN ssal AS b ON a.numero=b.numero
				JOIN sinv AS c on a.codigo=c.codigo
				WHERE a.id='$items4->id'
				GROUP BY a.id";
				
				$this->db->query($l_c_items);
				
				$i++;	
			}
	
		}
		
		//************************************
		//Ajustes de salida
		//************************************
		
		$query_2=$this->db->query("SELECT numero FROM ssal WHERE tipo='S' AND fecha BETWEEN '$fechai' AND '$fechaf'  AND tipo_doc='FC'");
		
		foreach($query_2->result() as $items2 ){
			
			$query_3=$this->db->query("SELECT id FROM itssal WHERE numero='$items2->numero'");
			
			$i=1;
			foreach($query_3->result() as $items3 ){
				
				$i=STR_PAD($i,5,0, STR_PAD_LEFT);
				
				$l_d_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  cuenta,  
				fdocu,  ccost, cprod,descrip,  dc, cant, monto, cambio,  monto_me, fecha)
				SELECT b.id,'ssal' as tabla,b.moneda,'L' comp,'010'seriei,a.numero,'$i'AS secu,'2001010000'cuenta,
				DATE_FORMAT(b.fecha, '%Y%m%d')fecha,'0002' ccosto, 
				c.csiigo,CONCAT(c.descrip,' ',c.descrip2) as desca,'C',INSERT(LPAD(a.cantidad,13,0), 14,14, '000')cantidad,
				LPAD(round(a.costomn*a.cantidad,2),16,0) monto,
				INSERT(LPAD((SELECT cambio FROM cambio AS f WHERE f.fecha=b.fecha),12,0), 13,13, '0000') cambio,
				LPAD(round(a.costome*a.cantidad,2),16,0) montoe,
				b.fecha	
				FROM itssal AS a
				JOIN ssal AS b ON a.numero=b.numero
				JOIN sinv AS c on a.codigo=c.codigo
				WHERE a.id='$items3->id'
				GROUP BY a.id";
				
				$this->db->query($l_d_items);
	
				$i++;		
			}
			
			foreach($query_3->result() as $items4 ){
				
				$i=STR_PAD($i,5,0, STR_PAD_LEFT);
				
				$l_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  cuenta,  
				fdocu,  ccost, cprod,descrip, dc, cant,monto, cambio,  monto_me, fecha)
				SELECT b.id,'ssal' as tabla,b.moneda,'L' comp,'010'seriei,a.numero,'$i'AS secu,'7509050000'cuenta,
				DATE_FORMAT(b.fecha, '%Y%m%d')fecha,'0002' ccosto, 
				c.csiigo,CONCAT(c.descrip,' ',c.descrip2) as desca,'D',INSERT(LPAD(a.cantidad,13,0), 14,14, '000')cantidad,
				LPAD(round(a.costomn*a.cantidad,2),16,0) monto,
				INSERT(LPAD((SELECT cambio FROM cambio AS f WHERE f.fecha=b.fecha),12,0), 13,13, '0000') cambio,
				LPAD(round(a.costome*a.cantidad,2),16,0) montoe,
				b.fecha	
				FROM itssal AS a
				JOIN ssal AS b ON a.numero=b.numero
				JOIN sinv AS c on a.codigo=c.codigo
				WHERE a.id='$items4->id'
				GROUP BY a.id";
				
				$this->db->query($l_c_items);
				
				$i++;	
			}
	
		}
        
		//************************************
		//Ajustes de Reverso
		//************************************
		
		$query_2=$this->db->query("SELECT numero FROM ssal WHERE tipo='R' AND fecha BETWEEN '$fechai' AND '$fechaf'  AND tipo_doc='FC'");
		
		foreach($query_2->result() as $items2 ){
			
			$query_3=$this->db->query("SELECT id FROM itssal WHERE numero='$items2->numero'");
			
			$i=1;
			foreach($query_3->result() as $items3 ){
				
				$i=STR_PAD($i,5,0, STR_PAD_LEFT);
				
				$l_d_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  cuenta,  
				fdocu,  ccost, cprod,descrip,  dc, cant, monto, cambio,  monto_me, fecha)
				SELECT b.id,'ssal' as tabla,b.moneda,'L' comp,'010'seriei,a.numero,'$i'AS secu,'2801011100'cuenta,
				DATE_FORMAT(b.fecha, '%Y%m%d')fecha,'0002' ccosto, 
				c.csiigo,CONCAT(c.descrip,' ',c.descrip2) as desca,'D',INSERT(LPAD(a.cantidad,13,0), 14,14, '000')cantidad,
				LPAD(round(a.costomn*a.cantidad,2),16,0) monto,
				INSERT(LPAD((SELECT cambio FROM cambio AS f WHERE f.fecha=b.fecha),12,0), 13,13, '0000') cambio,
				LPAD(round(a.costome*a.cantidad,2),16,0) montoe,
				b.fecha	
				FROM itssal AS a
				JOIN ssal AS b ON a.numero=b.numero
				JOIN sinv AS c on a.codigo=c.codigo
				WHERE a.id='$items3->id'
				GROUP BY a.id";
				
				$this->db->query($l_d_items);
	
				$i++;		
			}
			
			foreach($query_3->result() as $items4 ){
				
				$i=STR_PAD($i,5,0, STR_PAD_LEFT);
				
				$l_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  cuenta,  
				fdocu,  ccost, cprod,descrip, dc, cant,monto, cambio,  monto_me, fecha)
				SELECT b.id,'ssal' as tabla,b.moneda,'L' comp,'010'seriei,a.numero,'$i'AS secu,'2001010100'cuenta,
				DATE_FORMAT(b.fecha, '%Y%m%d')fecha,'0002' ccosto, 
				c.csiigo,CONCAT(c.descrip,' ',c.descrip2) as desca,'C',INSERT(LPAD(a.cantidad,13,0), 14,14, '000')cantidad,
				LPAD(round(a.costomn*a.cantidad,2),16,0) monto,
				INSERT(LPAD((SELECT cambio FROM cambio AS f WHERE f.fecha=b.fecha),12,0), 13,13, '0000') cambio,
				LPAD(round(a.costome*a.cantidad,2),16,0) montoe,
				b.fecha	
				FROM itssal AS a
				JOIN ssal AS b ON a.numero=b.numero
				JOIN sinv AS c on a.codigo=c.codigo
				WHERE a.id='$items4->id'
				GROUP BY a.id";
				
				$this->db->query($l_c_items);
				
				$i++;	
			}
	
		}
        //*******************************
        //costeo
        
        $query=$this->db->query("SELECT factura FROM costos WHERE origen='3I' and fecha BETWEEN '$fechai' AND '$fechaf' group by factura");
        
        foreach($query->result() as $items3 ){
			
			$query2=$this->db->query("SELECT idcosto,fecha,factura FROM costos WHERE  factura='$items3->factura'");
			
			$cant=$query2->num_rows();
			
			$i=1;
			
			foreach($query2->result() as $items2 ){
				
			$date=strtotime($items2->fecha);       
        	$year=date('Y',$date);
        	$mes=date('m',$date);
        	
        	$dia=substr($items2->factura,-5);
        	$mes=STR_PAD($mes,2,0, STR_PAD_LEFT);

			$numeroi=$year.$mes.$dia;
				
			$i=STR_PAD($i,5,0, STR_PAD_LEFT);
				
			
				$L="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,  cuenta,  
				fdocu,  ccost, cprod,descrip,  dc,  monto, cambio,monto_me,fecha)
				SELECT a.idcosto,'costos' as tabla,b.moneda,'L' comp,'013','$numeroi','$i'AS secu,
				LPAD(c.rucd,13,0) ruc,'000'sucu,'2001010100',
				DATE_FORMAT(a.fecha, '%Y%m%d')fecha,'0002'ccosto,b.csiigo,LEFT(CONCAT(b.descrip,' ',b.descrip2),50)as desca,'C',
				LPAD(round(a.costomn*a.egreso,2),16,0) monto,
				INSERT(LPAD((SELECT cambio FROM cambio AS f WHERE f.fecha=a.fecha),12,0), 13,13, '0000') cambio,
				LPAD(round(a.costome*a.egreso,2),16,0) montoe,
				a.fecha
				FROM costos AS a
				LEFT JOIN sinv AS b ON a.codigo=b.codigo
				LEFT JOIN remision as c on a.factura=c.nguia
				LEFT JOIN spre as d on d.numero=c.factura
				WHERE a.idcosto='$items2->idcosto'";
			
				$this->db->query($L);
			
				$i++;		
			
			}
			
			
			$j=$cant+1;
			
			foreach($query2->result() as $items4 ){
				
			$date=strtotime($items4->fecha);       
        	$year=date('Y',$date);
        	$mes=date('m',$date);
        	
        	$dia=substr($items4->factura,-5);
        	$mes=STR_PAD($mes,2,0, STR_PAD_LEFT);
        	
        	$numeroi=$year.$mes.$dia;
				
			$j=STR_PAD($j,5,0, STR_PAD_LEFT);
				
			
				$L="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,  cuenta,  
				fdocu,  ccost, cprod,descrip,  dc,  monto, cambio,monto_me,fecha)
				SELECT a.idcosto,'costos' as tabla,b.moneda,'L' comp,'013','$numeroi','$j'AS secu,
				LPAD(c.rucd,13,0) ruc,'000'sucu,'6901010100',
				DATE_FORMAT(a.fecha, '%Y%m%d')fecha,'0002'ccosto,b.csiigo,LEFT(CONCAT(b.descrip,' ',b.descrip2),50)as desca,'D',
               	LPAD(round(a.costomn*a.egreso,2),16,0) monto,
				INSERT(LPAD((SELECT cambio FROM cambio AS f WHERE f.fecha=a.fecha),12,0), 13,13, '0000') cambio,
				LPAD(round(a.costome*a.egreso,2),16,0) montoe,
				a.fecha
				FROM costos AS a
				LEFT JOIN sinv AS b ON a.codigo=b.codigo
				LEFT JOIN remision as c on a.factura=c.nguia
				LEFT JOIN spre as d on d.numero=c.factura
				WHERE a.idcosto='$items4->idcosto'";
			
				$this->db->query($L);
			
				$j++;		
			
			}
		
		}
        
        //****************************************************
        //Liquidacion de gasto
        
        $query=$this->db->query("SELECT transac FROM cruce WHERE fecha BETWEEN '$fechai' AND '$fechaf'");
        
        foreach($query->result() as $items2 ){
			
		$query=$this->db->query("SELECT id FROM itcruce WHERE transac='$items2->transac'");
        
		$i=1;
		$a=1;
		foreach($query->result() as $items ){
			
		$i=STR_PAD($i,5,0, STR_PAD_LEFT);
		$ii=STR_PAD($a,3,0, STR_PAD_LEFT);
						
			$L="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,  cuenta,  
			fdocu,  ccost, descrip,  dc,  monto,  cvend,cambio,  monto_me, 
			fecha,tdoc_cruce,sec_cruce,ccomp_cruce,num_cruce,fven_cruce)
			SELECT a.transac,'itcruce' as tabla,monedaori,'L' comp,seriei,a.numeroi,'$i'AS secu,LPAD(b.ruc,13,0) ruc,'000'sucu,b.cuenta,
			DATE_FORMAT(a.fecha, '%Y%m%d')fecha,ccosto, 
			IF(b.tipo='D',IF(condi1<>'',LEFT(condi1,50),desca),LEFT(desca,50))as desca,b.tipo,
			LPAD(importe*cambio,16,0) monto,
			'0000'vd,
			INSERT(LPAD(a.cambio,12,0), 13,13, '0000') cambio,
			LPAD(importe,16,0) montoe,
			a.fecha,b.tipod as doc_cruce,'$ii' sec_cruce,
			LPAD(b.seried,3,0)serie ,b.numerod as numero,
			DATE_FORMAT((SELECT fecha FROM sprm as s WHERE s.seriep=b.seried AND s.factura=b.numerod and s.proveed=b.proveed AND s.tipo_doc=b.tipod), '%Y%m%d')fecha
			FROM cruce AS a
			JOIN itcruce AS b ON a.transac=b.transac
			WHERE b.id='$items->id'";
		
			$this->db->query($L);
			
			//SELECT a.transac,'itcruce' as tabla,monedaori,'L' comp,seriei,a.numeroi,'$i'AS secu,LPAD(b.ruc,13,0) ruc,'000'sucu,b.cuenta,
			//DATE_FORMAT(a.fecha, '%Y%m%d')fecha,ccosto, 
			//IF(b.tipo='D',IF(condi1<>'',LEFT(condi1,50),desca),LEFT(desca,50))as desca,b.tipo,
			//LPAD(importe*cambio,16,0) monto,
			//'0000'vd,
			//INSERT(LPAD(a.cambio,12,0), 13,13, '0000') cambio,
			//LPAD(importe,16,0) montoe,
			//a.fecha,b.tipod as doc_cruce,'$ii' sec_cruce,
			//LPAD(b.seried,3,0)serie ,b.numerod as numero,
			//DATE_FORMAT((SELECT fecha FROM sprm as s WHERE s.seriep=b.seried AND s.factura=b.numerod and s.proveed=b.proveed AND s.tipo_doc=b.tipod), '%Y%m%d')fecha
			//FROM cruce AS a
			//JOIN itcruce AS b ON a.transac=b.transac
			
			//SELECT a.transac,'itcruce' as tabla,monedaori,'L' comp,seriei,a.numeroi,'$i'AS secu,LPAD(b.ruc,13,0) ruc,'000'sucu,b.cuenta,
			//DATE_FORMAT(a.fecha, '%Y%m%d')fecha,ccosto, 
			//IF(b.tipo='D',IF(condi1<>'',LEFT(condi1,50),desca),LEFT(desca,50))as desca,b.tipo,
			//if(b.monedaori='01',LPAD(ROUND(b.importemn,2),16,0),LPAD(ROUND(b.importe*a.cambio,2),16,0)) monto,
			//'0000'vd,
			//INSERT(LPAD(a.cambio,12,0), 13,13, '0000') cambio,
			//if(b.monedaori='02',LPAD(ROUND(b.importe,2),16,0),LPAD(ROUND(b.importemn/a.cambio,2),16,0)) montoe,
			//a.fecha,b.tipod as doc_cruce,'$ii' sec_cruce,
			//LPAD(b.seried,3,0)serie ,b.numerod as numero,
			//DATE_FORMAT((SELECT fecha FROM sprm as s WHERE s.seriep=b.seried AND s.factura=b.numerod and s.proveed=b.proveed AND s.tipo_doc=b.tipod), '%Y%m%d')fecha
			//FROM cruce AS a
			//JOIN itcruce AS b ON a.transac=b.transac
		
			$i++;
			$a++;
		
		
			}
		}
        
        //****************************************************
		//Facturas de Gasto
		
		$query=$this->db->query("SELECT transac FROM gser WHERE fecha BETWEEN '$fechai' AND '$fechaf' AND comp='L' AND seriei<>'007'");
		
		foreach($query->result() as $items ){
			
		$query_2=$this->db->query("SELECT id,cuenta,transac FROM gitser WHERE transac='$items->transac'");
		$cant   =$this->datasis->dameval("SELECT COUNT(*) FROM gitser WHERE transac='$items->transac'");
		$cuenta =$this->datasis->dameval("SELECT cuenta FROM gitser WHERE transac='$items->transac' LIMIT 1");
		$viva   =$this->datasis->dameval("SELECT totiva FROM gser WHERE transac='$items->transac'");
		$comp   =$this->datasis->dameval("SELECT comp FROM gser WHERE transac='$items->transac'");
		
		IF($viva>0){
			$vigv=$igv;
			$ind_tmovi='S';
			$coa='S';
			
		}else{
			
			$vigv=0;
			$ind_tmovi='B';
			$coa='B';
			
		}
		
		$m1=$cant+1;
		$m2=$cant+2;
		$m3=$cant+3;
		$m4=$cant+4;
		
		$m1=STR_PAD($m1,5,0, STR_PAD_LEFT);	
		$m2=STR_PAD($m2,5,0, STR_PAD_LEFT);
		$m3=STR_PAD($m3,5,0, STR_PAD_LEFT);
		$m4=STR_PAD($m4,5,0, STR_PAD_LEFT);
		  
		$P_c_cp="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,  cuenta,tdoc_cruce,ccomp_cruce,num_cruce,sec_cruce,fven_cruce,
		fdocu,  ccost, descrip,  dc,  monto,  cvend, cambio,  monto_me,fecha,formap,ncom_prov,ndoc_prov,fdoc_prov,cpago)
		SELECT a.transac,'gser' as tabla,moneda,'L' comp,seriei,a.numeroi,'$m1'AS secu,LPAD(rif,13,0) ruc,'000'sucu,cuenta,'P',a.seriep,a.numero,'001'secu,DATE_FORMAT(a.vence, '%Y%m%d')fecha,
		DATE_FORMAT(a.fecha, '%Y%m%d')fecha,ccosto, 
		CONCAT(condi1,' ',seriep,'-',numero)descrip,'C',
		if(a.moneda='01',LPAD(ROUND(a.totbruto,2),16,0),LPAD(ROUND(a.totbruto*cambio,2),16,0)) monto,
		'0000'vd,INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(moneda='01',LPAD(ROUND(a.totbruto/cambio,2),16,0),LPAD(a.totbruto,16,0)) montoe,a.fecha,LPAD(formap,4,0),
		LPAD(a.seriep,4,0),a.numero,DATE_FORMAT(a.fecha, '%Y%m%d')fecha,a.numero		
		FROM gser AS a
		WHERE a.transac='$items->transac'";
		
		$this->db->query($P_c_cp);
		
		IF($viva>0){
		
			$P_c_iva="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,cuenta,tdoc_cruce,ccomp_cruce,num_cruce,sec_cruce,fven_cruce,  
			fdocu,  ccost, descrip,  dc,  monto,  cvend, cambio,  monto_me,fecha,ncom_prov,ndoc_prov,fdoc_prov,cpago)
			SELECT a.transac,'gser' as tabla,moneda,'L' comp,seriei,a.numeroi,'$m2'AS secu,LPAD(rif,13,0) ruc,'000'sucu,'$iva','P',a.seriep,a.numero,'001'secu,DATE_FORMAT(a.vence, '%Y%m%d')fecha,
			DATE_FORMAT(a.fecha, '%Y%m%d')fecha,ccosto, 
			CONCAT('IVA DEL DOCUMENTO ',seriep,'-',numero)descrip,'D',
			if(a.moneda='01',LPAD(ROUND(a.totiva,2),16,0),LPAD(ROUND(a.totiva*cambio,2),16,0)) monto,
			'0000'vd,INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			IF(moneda='01',LPAD(ROUND(a.totiva/cambio,2),16,0),LPAD(a.totiva,16,0)) montoe,a.fecha,
			LPAD(a.seriep,4,0),a.numero,DATE_FORMAT(a.fecha, '%Y%m%d')fecha,a.numero
			FROM gser AS a
			WHERE a.transac='$items->transac'";
			
			$this->db->query($P_c_iva);
		
		}
		
	   IF($viva>0){
		
			$m3=$m3-1;
			$m4=$m4-1;
		
		}else{
			
			$m3=$m2-1;
			$m4=$m2;	
		}
	   
	   
	   $query_1=$this->db->query("SELECT b.id,b.transac,b.cuenta FROM gitser as b JOIN gser as a ON a.transac=b.transac 
       WHERE b.transac='$items->transac' AND b.cuenta like '9%'");
       
       foreach($query_1->result() as $items1 ){
              
       $m4=$m4+1; 
       $m3=$m3+1;
       
       $m3=STR_PAD($m3,5,0, STR_PAD_LEFT);
       $m4=STR_PAD($m4,5,0, STR_PAD_LEFT); 
           		
			$ajuste=$this->datasis->dameval("SELECT ajuste FROM cpla WHERE cuenta='$items1->cuenta'");
			
            IF (!empty($ajuste)){		
			
            $P_aj="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,  cuenta,  
			fdocu,  ccost, descrip,  dc,  monto,  cvend,cambio,  monto_me, fecha,ind_tmovi,piva,viva,ncom_prov,ndoc_prov,fdoc_prov,cpago,met_depre,pcargo,fven_cruce)
			SELECT a.transac,'gser' as tabla,moneda,'L' comp,a.seriei,a.numeroi,'$m3'AS secu,LPAD(rif,13,0) ruc,'000'sucu,'$ajuste',
			DATE_FORMAT(a.fecha, '%Y%m%d')fecha,ccosto, 
            IF(b.tipo='D',IF(condi1<>'',LEFT(condi1,50),desca),LEFT(desca,50))as descrip,'D',
			if(a.moneda='01',LPAD(ROUND(b.preca,2),16,0),LPAD(ROUND(b.preca*cambio,2),16,0)) monto,
			'0000'vd,INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			IF(moneda='01',LPAD(ROUND(b.preca/cambio,2),16,0),LPAD(b.preca,16,0)) montoe,
			a.recepcion,'$ind_tmovi',RPAD('$vigv',4,0) as piva,LPAD(ROUND((b.preca*'$vigv'/100),2),14,0) viva,LPAD(a.seriep,4,0),a.numero,DATE_FORMAT(a.fecha, '%Y%m%d')fecha,a.numero,'$coa',RPAD('$vigv',4,0) as pcargo,	
			DATE_FORMAT(a.vence, '%Y%m%d')fecha
			FROM gser AS a
			JOIN gitser AS b ON a.transac=b.transac
			WHERE a.transac='$items1->transac' and b.id='$items1->id'";
			
			$this->db->query($P_aj);
            
            }
			
			$contrapartida=$this->datasis->dameval("SELECT contrapartida FROM cpla WHERE cuenta='$items1->cuenta'");
			
            IF (!empty($contrapartida)){
                
			$P_cont="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,  cuenta,  
			fdocu,  ccost, descrip,  dc,  monto,  cvend,cambio,  monto_me, fecha,ind_tmovi,piva,viva,ncom_prov,ndoc_prov,fdoc_prov,cpago,met_depre,pcargo,fven_cruce)
			SELECT a.transac,'gser' as tabla,moneda,'L' comp,a.seriei,a.numeroi,'$m4'AS secu,LPAD(rif,13,0) ruc,'000'sucu,'$contrapartida',
			DATE_FORMAT(a.fecha, '%Y%m%d')fecha,ccosto, 
			CONCAT('CARGOS IMPUTABLES A CUENTAS DE COSTOS ')descrip,'C',
			if(a.moneda='01',LPAD(ROUND(b.preca,2),16,0),LPAD(ROUND(b.preca*cambio,2),16,0)) monto,
			'0000'vd,INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			IF(moneda='01',LPAD(ROUND(b.preca/cambio,2),16,0),LPAD(b.preca,16,0)) montoe,
			a.recepcion,'$ind_tmovi',RPAD('$vigv',4,0) as piva,LPAD(ROUND((b.preca*'$vigv'/100),2),14,0) viva,LPAD(a.seriep,4,0),a.numero,DATE_FORMAT(a.fecha, '%Y%m%d')fecha,a.numero,'$coa',RPAD('$vigv',4,0) as pcargo,	
			DATE_FORMAT(a.vence, '%Y%m%d')fecha
			FROM gser AS a
			JOIN gitser AS b ON a.transac=b.transac
			WHERE a.transac='$items1->transac' and b.id='$items1->id'";
					
			$this->db->query($P_cont);	
            
            }
            
            $m3++;
            $m4++;
        }
		
		$i=1;	
						
		foreach($query_2->result() as $detalle ){
		
			$i=STR_PAD($i,5,0, STR_PAD_LEFT);
		
			$P_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,  cuenta,  
			fdocu,  ccost, descrip,  dc,  monto,  cvend,cambio,  monto_me, fecha,ind_tmovi,piva,viva,ncom_prov,ndoc_prov,fdoc_prov,cpago,met_depre,pcargo,fven_cruce,tdoc_cruce,num_cruce,ccomp_cruce)
			SELECT a.transac,'gser' as tabla,moneda,'L' comp,seriei,a.numeroi,'$i'AS secu,LPAD(rif,13,0) ruc,'000'sucu,b.cuenta,
			DATE_FORMAT(a.fecha, '%Y%m%d')fecha,ccosto,b.desca as desca,b.tipo,
			if(a.moneda='01',LPAD(ROUND(b.preca,2),16,0),LPAD(ROUND(b.preca*cambio,2),16,0)) monto,
			'0000'vd,INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			IF(moneda='01',LPAD(ROUND(b.preca/cambio,2),16,0),LPAD(b.preca,16,0)) montoe,
			a.fecha,'$ind_tmovi',RPAD('$vigv',4,0) as piva,LPAD(ROUND((b.preca*'$vigv'/100),2),14,0) viva,LPAD(a.seriep,4,0),a.numero,DATE_FORMAT(a.fecha, '%Y%m%d')fecha,a.numero,'$coa',RPAD('$vigv',4,0) as pcargo,	
			DATE_FORMAT(a.vence, '%Y%m%d')fecha,
			IF((SELECT COUNT(*) FROM scli as s WHERE a.proveed=s.cliente)>0 AND b.tipoc IN ('AN'),'R',IF(b.tipoc='NC','C',IF(b.tipoc='ND','D',IF((SELECT COUNT(*) FROM sprv as v WHERE a.proveed=v.proveed)>0 AND b.tipoc IN ('AN','AR','EC'),'G',b.tipoc))))tipoc,
			b.factura,IF(tipoc='L' AND (SELECT COUNT(*) FROM scli as s WHERE a.proveed=s.cliente)>0,'LTR',b.serief) AS serief
			FROM gser AS a
			JOIN gitser AS b ON a.transac=b.transac
			WHERE b.id='$detalle->id'";
			
			$this->db->query($P_c_items);	
		
			$i++;
		}		
			
     }
     
     $this->db->query("DELETE FROM comprobantes WHERE tcomp='L' AND monto='0000000000000.00'");

	}			
    function _l2($fechai,$fechaf){
		
		$this->db->query("DELETE FROM comprobantes WHERE tcomp='L' AND ccomp='006' AND fecha BETWEEN '$fechai' AND '$fechaf' AND tabla<>'siigo'");
        
        //****************************************************
		//Letras 
		
	    //Genera Comprobantes L 
	    
		$query=$this->db->query("SELECT a.id
		FROM itpagos AS a
		WHERE fecha BETWEEN '$fechai' AND '$fechaf' AND compro='L' AND observa<>'CREADA POR ADMIN SIIGO_2013'
		GROUP BY a.numero
		ORDER BY numero");
				
		
		foreach($query->result() as $items ){
			
			
			$query=$this->db->query("SELECT a.id,a.moneda,a.serie,a.numero
			FROM itpagos AS a
			WHERE a.id='$items->id'");
		
		
			
		$a=1;
			
		foreach($query->result() as $items_1 ){	
			
				$cuenta=$this->cuenta->cxc($items_1->moneda);
				
				$L_c="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
				fdocu,  ccost,  descrip,  dc,  monto,
				cambio,  monto_me, tdoc_cruce,ccomp_cruce,num_cruce,fven_cruce,sec_cruce,fecha,tip_letra,cvend)	
				SELECT a.id,'letras'as tabla, moneda,'L',a.serie,a.numero,LPAD((@rownum:=@rownum+1),5,0) AS secu,
				a.ruc,a.cuenta,fecha_docu,ccosto,descrip,dc,monto,cambio,montoe,doc_cruce,serie_cruce,
				num_cruce,vence,sec_cruce,fecha,letra,cvend
				FROM (SELECT a.id,'letras'as tabla, moneda,'L',a.serie,a.numero,
				LPAD(c.rifci,13,0) ruc,if(b.serief='LTR',a.cuenta,'$cuenta') cuenta,
				DATE_FORMAT(a.fecha, '%Y%m%d')fecha_docu,'001' ccosto,
				CONCAT('CANJE DE ',if(b.serief='LTR','L',IF((select tipo_doc from smov as s where s.transac=b.transac)='ND','D','F')),if(b.serief='LTR','LTR','001'),'-',b.factura)as descrip, 
				'C' dc,
				if(a.moneda='01',LPAD(SUM(b.monto),16,0),LPAD(SUM(b.monto)*a.cambio,16,0)) monto,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
				IF(a.moneda='01',LPAD(ROUND(SUM(b.monto)/a.cambio,2),16,0),	LPAD(SUM(b.monto),16,0)) montoe,
				if(b.serief='LTR','L',IF((select tipo_doc from smov as s where s.transac=b.transac)='ND','D','F'))as doc_cruce,if(b.serief='LTR','LTR','001') AS serie_cruce,b.factura num_cruce,DATE_FORMAT(vence, '%Y%m%d')vence,'001' sec_cruce,
				fecha,'L'as letra,'0000'cvend	
				FROM itpagos AS a
				JOIN letras  AS b ON a.id=b.idpago
				JOIN scli    AS c ON a.cod_cli=c.cliente
				WHERE compro IN ('L') AND a.numero='$items_1->numero'
				GROUP BY factura )a,(SELECT @rownum:=0)b";
				//echo $L_c.'</br>';
				$this->db->query($L_c);
				
				
				$count=$this->db->query("SELECT a.id
				FROM itpagos AS a
				JOIN letras  AS b ON a.id=b.idpago
				WHERE compro='L' AND a.numero='$items_1->numero'
				GROUP BY factura");
				
				$j=$count->num_rows();
				$i=1;
				
				$ii   =STR_PAD($i,3,0, STR_PAD_LEFT);
				
				$L_d="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
				fdocu,  ccost,  descrip,  dc,  monto,
				cambio,  monto_me, tdoc_cruce,ccomp_cruce,num_cruce,fven_cruce,sec_cruce,fecha,tip_letra,est_letra,cvend)	
				SELECT a.id,'letras'as tabla, moneda,'L',a.serie,a.numero,LPAD((@rownum:=@rownum+1),5,0) AS secu,
				a.ruc,a.cuenta,fecha_docu,ccosto,descrip,dc,monto,cambio,montoe,doc_cruce,serie_cruce,
				num_cruce,vence,sec_cruce,fecha,letra,est_letra,cvend
				FROM (SELECT a.id,'letras'as tabla, moneda,'L',a.serie,a.numero,
				LPAD(c.rifci,13,0) ruc,cuenta,
				DATE_FORMAT(a.fecha, '%Y%m%d')fecha_docu,'001' ccosto,
				CONCAT('LETRA ',a.tipo,' NUMERO ',a.control,' CREADA') as descrip, 
				'D' dc,
				if(a.moneda='01',LPAD(SUM(b.monto),16,0),LPAD(SUM(b.monto)*a.cambio,16,0)) monto,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
				IF(a.moneda='01',LPAD(ROUND(SUM(b.monto)/a.cambio,2),16,0),	LPAD(SUM(b.monto),16,0)) montoe,
				'L' as doc_cruce,'LTR' as serie_cruce,control num_cruce,DATE_FORMAT(vence, '%Y%m%d')vence,'$ii' sec_cruce,
				fecha,'L' letra,'A' est_letra,'0000' cvend	
				FROM itpagos AS a
				JOIN letras  AS b ON a.id=b.idpago
				JOIN scli    AS c ON a.cod_cli=c.cliente
				WHERE compro='L' AND a.numero='$items_1->numero'
				GROUP BY control )a,(SELECT @rownum:='$j')b";
				
				
				$this->db->query($L_d);

						
			}	
				
		}
	}	
    function _l2san($fechai,$fechaf){
        
        $this->db->query("DELETE FROM comprobantes WHERE tcomp='L' AND ccomp='006' AND fecha BETWEEN '$fechai' AND '$fechaf' AND tabla<>'siigo'");
        
        		//****************************************************
		//Letras 
		
	    
	    //Genera Comprobantes L 
	    
		$query=$this->db->query("SELECT a.id,numero,moneda
		FROM itpagos AS a
		WHERE fecha BETWEEN '$fechai' AND '$fechaf' AND compro='L'");			
		
		foreach($query->result() as $items ){
			
		$cuenta=$this->cuenta->cxc($items->moneda);	
			
		$query_1=$this->db->query("SELECT factura,idpago,numero,control 
		FROM  itpagos as a
		JOIN  letras as b ON a.id=b.idpago 
		WHERE idpago='$items->id' AND compro='L'
		GROUP BY factura");
		
		$cant=$this->datasis->dameval("SELECT COUNT(*) FROM  letras WHERE idpago='$items->id' AND factura=factura");
		$a=1;
		
        
		foreach($query_1->result() as $items_1 ){
			
		$count=$this->db->query("SELECT  COUNT(*) FROM itpagos AS a
		JOIN letras  AS b ON a.id=b.idpago
		WHERE compro='L' AND a.numero='$items->numero'
		GROUP BY  b.factura");
			
			//IF($cant==1){
				
				$chek=$this->datasis->dameval("SELECT COUNT(*) FROM comprobantes WHERE tcomp='L' AND ccomp='006' AND ncomp='$items_1->numero' AND num_cruce='$items_1->factura'");	
				if($chek==0){
					
				$secu1=STR_PAD($a,5,0, STR_PAD_LEFT);
					
					$L_c="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
					fdocu,  ccost,  descrip,  dc,  monto,
					cambio,  monto_me, tdoc_cruce,ccomp_cruce,num_cruce,fven_cruce,sec_cruce,fecha,tip_letra,cvend)	
					SELECT a.id,'itpagos'as tabla, moneda,'L',a.serie,a.numero,'$secu1' AS secu,
					LPAD(rifci,13,0) ruc,'$cuenta',
					DATE_FORMAT(fecha, '%Y%m%d')fecha,'001' ccosto,
					CONCAT('CANJE DE FACTURA ',b.serief,'-',b.factura)as descrip, 
					'C',
					if(a.moneda='01',LPAD(SUM(b.monto),16,0),LPAD(SUM(b.monto)*a.cambio,16,0)) monto,
					INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
					IF(a.moneda='01',LPAD(ROUND(SUM(b.monto)/a.cambio,2),16,0),
					LPAD(SUM(b.monto),16,0)) montoe,
					'F'as doc_cruce,b.serief as serie_cruce,b.factura num_cruce,DATE_FORMAT(vence, '%Y%m%d')vence,'001' sec_cruce,
					fecha,'L','0000'	
					FROM itpagos AS a
					JOIN letras  AS b ON a.id=b.idpago
					JOIN scli    AS c ON a.cod_cli=c.cliente
					WHERE compro='L' AND a.numero='$items->numero' AND factura='$items_1->factura'
                    GROUP BY compro,numero,factura";
					//echo $L_c.'</br>';
					$this->db->query($L_c);
					$a++;
				}
				
			
			//}else{	
			//		$secu1=STR_PAD($a,5,0, STR_PAD_LEFT);
			//						
			//		$L_c="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
			//		fdocu,  ccost,  descrip,  dc,  monto,
			//		cambio,  monto_me, tdoc_cruce,ccomp_cruce,num_cruce,fven_cruce,sec_cruce,fecha,tip_letra,cvend)	
			//		SELECT a.id,'itpagos'as tabla, moneda,'L',a.serie,a.numero,'$secu1' AS secu,
			//		LPAD(rifci,13,0) ruc,'$cuenta',
			//		DATE_FORMAT(fecha, '%Y%m%d')fecha,'001' ccosto,
			//		CONCAT('CANJE DE FACTURA ',b.serief,'-',b.factura)as descrip, 
			//		'C',
			//		if(a.moneda='01',LPAD(SUM(b.monto),16,0),LPAD(SUM(b.monto)*a.cambio,16,0)) monto,
			//		INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			//		IF(a.moneda='01',LPAD(ROUND(SUM(b.monto)/a.cambio,2),16,0),
			//		LPAD(SUM(b.monto),16,0)) montoe,
			//		'F'as doc_cruce,b.serief as serie_cruce,b.factura num_cruce,DATE_FORMAT(vence, '%Y%m%d')vence,'001' sec_cruce,
			//		fecha,'L','0000'	
			//		FROM itpagos AS a
			//		JOIN letras  AS b ON a.id=b.idpago
			//		JOIN scli    AS c ON a.cod_cli=c.cliente
			//		WHERE compro='L' AND factura='$items_1->factura' AND a.id='$items_1->idpago'";
			//		//echo $L_c.'</br>';
			//
			//		$this->db->query($L_c);
			//		$a++;
			//	}
				
		//*************************************	
		
		IF($cant>1){
							
				$b=$count->num_rows();	
				$b=$b+1;
				$secu2=STR_PAD($b,5,0, STR_PAD_LEFT);
				
				$chek=$this->datasis->dameval("SELECT COUNT(*) FROM comprobantes WHERE tcomp='L' AND ccomp='006' AND ncomp='$items_1->numero' AND num_cruce=$items_1->control");	
			
				IF($chek==0){
				
					$L_d="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
					fdocu,  ccost,  descrip,  dc,  monto,
					cambio,  monto_me, tdoc_cruce,ccomp_cruce,num_cruce,fven_cruce,sec_cruce,fecha,tip_letra,est_letra,cvend)	
					SELECT  a.id,'itpagos'as tabla,moneda,'L',serie,numero,'$secu2'AS secu,
					LPAD(rifci,13,0) ruc,cuenta,
					DATE_FORMAT(fecha, '%Y%m%d')fecha,'001'ccosto, 
					CONCAT('LETRA  ',a.tipo,' NUMERO ',a.control,' CREADA') as descrip,'D',
					if(a.moneda='01',LPAD(a.monto,16,0),LPAD(a.monto*a.cambio,16,0)) monto,
					INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
					IF(a.moneda='01',LPAD(ROUND(a.monto/a.cambio,2),16,0),
					LPAD(a.monto,16,0)) montoe,
					'L'as doc_cruce,'LTR' as serie_cruce,control num_cruce,DATE_FORMAT(vence, '%Y%m%d')vence,'001' sec_cruce,fecha,'L','A','0000'	
					FROM itpagos AS a
					JOIN scli    AS c ON a.cod_cli=c.cliente
					WHERE a.id='$items->id'";
					$this->db->query($L_d);
				}
			
			
		}else{
	    
			$chek=$this->datasis->dameval("SELECT COUNT(*) FROM  letras WHERE idpago='$items->id'");
			
			IF($chek>1){
			
			$c=2;
			$i=1;
			
			$query_2=$this->db->query("SELECT id FROM  letras WHERE idpago='$items->id'");	
			
			foreach($query_2->result() as $items ){
				
				$secu2=STR_PAD($c,5,0, STR_PAD_LEFT);		
				$ii   =STR_PAD($i,3,0, STR_PAD_LEFT);
				
															
					$L_d="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
					fdocu,  ccost,  descrip,  dc,  monto,
					cambio,  monto_me, tdoc_cruce,ccomp_cruce,num_cruce,fven_cruce,sec_cruce,fecha,tip_letra,est_letra,cvend)	
					SELECT  a.id,'itpagos'as tabla,moneda,'L',serie,numero,'$secu2'AS secu,
					LPAD(rifci,13,0) ruc,cuenta,
					DATE_FORMAT(fecha, '%Y%m%d')fecha,'001'ccosto, 
					CONCAT('LETRA  ',a.tipo,' NUMERO ',a.control,' CREADA') as descrip,'D',
					if(a.moneda='01',LPAD(a.monto,16,0),LPAD(a.monto*a.cambio,16,0)) monto,
					INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
					IF(a.moneda='01',LPAD(ROUND(a.monto/a.cambio,2),16,0),
					LPAD(a.monto,16,0)) montoe,
					'L'as doc_cruce,'LTR' as serie_cruce,control num_cruce,DATE_FORMAT(vence, '%Y%m%d')vence,'$ii' sec_cruce,fecha,'L','A','0000'	
					FROM itpagos AS a
					JOIN letras  AS b ON a.id=b.idpago
					JOIN scli    AS c ON a.cod_cli=c.cliente
					WHERE b.id='$items->id'";
					$this->db->query($L_d);
					$i++;
					$c++;
					
				}
			}else{
				
				$i=1;
				$s=$this->datasis->dameval("SELECT COUNT(*) FROM comprobantes WHERE tcomp='L' AND ccomp='006' AND ncomp='$items->numero' AND dc='D'");				
				$c=$count->num_rows();
				$c=$c+$s+1;
				
				$query_2=$this->db->query("SELECT b.id,factura,idpago,numero,control 
				FROM  itpagos as a
				JOIN  letras as b ON a.id=b.idpago
				WHERE numero='$items->numero' AND compro='L'");	
				//WHERE factura='$items_1->factura' AND compro='L'");	
						
				
				foreach($query_2->result() as $items_3 ){
										
					$secu2=STR_PAD($c,5,0, STR_PAD_LEFT);		
					$ii   =STR_PAD($i,3,0, STR_PAD_LEFT);
					
					$r="SELECT COUNT(*) FROM comprobantes WHERE tcomp='L' AND ccomp='006' AND ncomp='$items_3->numero' AND num_cruce='$items_3->control'";
					$chek=$this->datasis->dameval($r);
					
																	
					//echo $r.' cant:'.$chek.'</br>';
					IF($chek==0){
        
						$L_d="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit, cuenta,  
						fdocu,  ccost,  descrip,  dc,  monto,
						cambio,  monto_me, tdoc_cruce,ccomp_cruce,num_cruce,fven_cruce,sec_cruce,fecha,tip_letra,est_letra,cvend)	
						SELECT  a.id,'itpagos'as tabla,moneda,'L',serie,numero,'$secu2'AS secu,
						LPAD(rifci,13,0) ruc,cuenta,
						DATE_FORMAT(fecha, '%Y%m%d')fecha,'001'ccosto, 
						CONCAT('LETRA ',a.tipo,' NUMERO ',a.control,' CREADA') as descrip,'D',
						if(a.moneda='01',LPAD(a.monto,16,0),LPAD(a.monto*a.cambio,16,0)) monto,
						INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
						IF(a.moneda='01',LPAD(ROUND(a.monto/a.cambio,2),16,0),
						LPAD(a.monto,16,0)) montoe,
						'L'as doc_cruce,'LTR' as serie_cruce,control num_cruce,DATE_FORMAT(vence, '%Y%m%d')vence,'$ii' sec_cruce,fecha,'L','A','0000'	
						FROM itpagos AS a
						JOIN letras  AS b ON a.id=b.idpago
						JOIN scli    AS c ON a.cod_cli=c.cliente
						WHERE b.id='$items_3->id'";
						//echo $chek.' '.$L_d.'</br>';
						$this->db->query($L_d);
						$i++;
						$c++;
					}
						
					}
				
                }
            }		
				
        }
		
	 }
        
    }
    function _d($fechai,$fechaf){
        
        $iva=$this->cuenta->iva();
		$igv=$this->datasis->traevalor('IGV');
        
        $this->db->query("DELETE FROM comprobantes WHERE tcomp='D' AND fecha BETWEEN '$fechai' AND '$fechaf' AND tabla<>'siigo' AND tabla IN ('notasdc','itnotasdc')");
        
        //****************************************************
		//Notas de Debito Cliente
		
		$query=$this->db->query("SELECT id FROM notasdc WHERE fecha BETWEEN '$fechai' AND '$fechaf'AND tipo_doc='ND'");
		
		foreach($query->result() as $items ){
			
		$query_2=$this->db->query("SELECT id_nota as id FROM itnotasdc WHERE id='$items->id'");
		$cant=$this->datasis->dameval("SELECT COUNT(*) FROM itnotasdc WHERE id='$items->id'");
		
		$m1=$cant+1;
		$m2=$cant+2;
		
		$m1=STR_PAD($m1,5,0, STR_PAD_LEFT);	
		$m2=STR_PAD($m2,5,0, STR_PAD_LEFT);
		
		$F_d_cc="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
		fdocu,  ccost, descrip,  dc,cciud,  monto,    
		cambio,  monto_me, tdoc_cruce,ccomp_cruce,num_cruce,sec_cruce,fven_cruce,formap, fecha)
		SELECT a.id,'notasdc' as tabla,moneda,'D','002',a.numero,'$m1'AS secu,LPAD(rifci,13,0) ruc,cuenta,
		DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto,
		CONCAT('CUENTA POR COBRAR ',a.serie,'-',a.numero) descrip,'D','0013',
		if(a.moneda='01',LPAD(ROUND(a.totalg,2),16,0),LPAD(ROUND(a.totalg*cambio,2),16,0)) monto,
		INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(a.moneda='01',LPAD(ROUND(a.totalg/a.cambio,2),16,0),
		LPAD(a.totalg,16,0)) montoe,compro,serief,factura,'001',DATE_FORMAT(fechaf, '%Y%m%d')vence,
		LPAD(formap,4,0) cod_formap,fecha	
		FROM notasdc AS a WHERE tipo_doc='ND'
		AND id='$items->id'";
				
		$this->db->query($F_d_cc);	
				
		$F_c_iva="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
		fdocu,  ccost, descrip,  dc,  monto,    
		cambio,  monto_me,fecha)			
		SELECT a.id,'notasdc' as tabla,moneda,'D','002',a.numero,'$m2'AS secu,LPAD(rifci,13,0) ruc,'$iva',
		DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto,
		CONCAT('IVA DEL DOCUMENTO ',a.serie,'-',a.numero) descrip,'C',
		if(a.moneda='01',LPAD(ROUND(a.iva,2),16,0),LPAD(ROUND(a.iva*cambio,2),16,0)) monto,
		INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(a.moneda='01',LPAD(ROUND(a.iva/a.cambio,2),16,0),LPAD(a.iva,16,0)) montoe,fecha	
		FROM notasdc AS a WHERE tipo_doc='ND'
		AND id='$items->id'";
		
		$this->db->query($F_c_iva);
		
		$i=1;	
						
		foreach($query_2->result() as $detalle ){
		
		$ii =STR_PAD($i,5,0, STR_PAD_LEFT);
		$j  =STR_PAD($i,3,0, STR_PAD_LEFT);
			
				$F_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
				fdocu,  ccost, descrip,dc,cciud,monto,cambio,  monto_me,fecha,pcargo,ind_tmovi,viva)	
				SELECT a.id,'notasdc' as tabla,b.moneda,'D','002',a.numero,'$ii'AS secu,LPAD(rifci,13,0) ruc,a.cuenta,
				DATE_FORMAT(fecha, '%Y%m%d')fecha,b.ccosto, a.descrip,'C',
				'0013'ciudad,
				if(b.moneda='01',LPAD(ROUND(a.total,2),16,0),LPAD(ROUND(a.total*cambio,2),16,0)) monto,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,				
				IF(b.moneda='01',LPAD(ROUND(a.total/cambio,2),16,0),
				LPAD(round(a.total,2),16,0)) montoe,	
				fecha,RPAD('$igv',4,0),'S',
				LPAD(ROUND((a.total*'$igv'/100),2),14,0) viva	
				FROM itnotasdc AS a
				JOIN notasdc AS b ON a.id=b.id AND b.tipo_doc='ND'
				WHERE id_nota='$detalle->id'"; 
						
				$this->db->query($F_c_items);
				$i++;
			}
			
		}   
    }
    function _c($fechai,$fechaf){
        
        $items_fc='7009010100';
        $iva=$this->cuenta->iva();
		$igv=$this->datasis->traevalor('IGV');
        
        $this->db->query("DELETE FROM comprobantes WHERE tcomp='C' AND fecha BETWEEN '$fechai' AND '$fechaf' AND tabla<>'siigo'");
        
        //****************************************************
		//Notas de Credito Cliente
		
		$query=$this->db->query("SELECT almacen,id FROM notascc WHERE fecha BETWEEN '$fechai' AND '$fechaf'AND tipo_doc='NC'");
		
		foreach($query->result() as $items ){
			
		$query_2=$this->db->query("SELECT id_nota as id,codigo as cuenta,LPAD(codigo,1,1) as ccuenta FROM itnotascc WHERE id='$items->id'");
		$cant=$this->datasis->dameval("SELECT COUNT(*) FROM itnotascc WHERE id='$items->id'");
		
		//$m1=$cant+1;
		//$m2=$cant+2;
		
		//$m1=STR_PAD($m1,5,0, STR_PAD_LEFT);	
		//$m2=STR_PAD($m2,5,0, STR_PAD_LEFT);
		
		$F_d_cc="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
		fdocu,  ccost, descrip,  dc,cciud,  monto,    
		cambio,  monto_me, tdoc_cruce,ccomp_cruce,num_cruce,sec_cruce,fven_cruce,formap, fecha)
		SELECT a.id,'notascc' as tabla,moneda,'C',a.serie,a.numero,'00001'AS secu,LPAD(rifci,13,0) ruc,cuenta,
		DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto,
		CONCAT('CUENTA POR COBRAR ',a.serie,'-',a.numero) descrip,'C','0013',
		if(a.moneda='01',LPAD(ROUND(a.totalg,2),16,0),LPAD(ROUND(a.totalg*cambio,2),16,0)) monto,
		INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(a.moneda='01',LPAD(ROUND(a.totalg/a.cambio,2),16,0),
		LPAD(a.totalg,16,0)) montoe,'F',serief,factura,'001',DATE_FORMAT(fechaf, '%Y%m%d')vence,
		LPAD(formap,4,0) cod_formap,fecha	
		FROM notascc AS a WHERE tipo_doc='NC'
		AND id='$items->id'";
				
		$this->db->query($F_d_cc);	
				
		$F_c_iva="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
		fdocu,  ccost, descrip,  dc,  monto,    
		cambio,  monto_me,fecha)			
		SELECT a.id,'notascc' as tabla,moneda,'C',a.serie,a.numero,'00002'AS secu,LPAD(rifci,13,0) ruc,'$iva',
		DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto,
		CONCAT('IVA DEL DOCUMENTO ',a.serie,'-',a.numero) descrip,'D',
		if(a.moneda='01',LPAD(ROUND(a.iva,2),16,0),LPAD(ROUND(a.iva*cambio,2),16,0)) monto,
		INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(a.moneda='01',LPAD(ROUND(a.iva/a.cambio,2),16,0),LPAD(a.iva,16,0)) montoe,fecha	
		FROM notascc AS a WHERE tipo_doc='NC'
		AND id='$items->id'";
		
		$this->db->query($F_c_iva);
		
		$i=3;
		
		IF($items->almacen<>'0000'){	
						
		foreach($query_2->result() as $detalle ){
		
		$ii =STR_PAD($i,5,0, STR_PAD_LEFT);
		$j  =STR_PAD($i,3,0, STR_PAD_LEFT);
			
				$F_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
				fdocu,  ccost, cprod,descrip,dc,cciud,monto,cambio,  monto_me,fecha,pcargo,ind_tmovi,viva,met_depre)	
				SELECT a.id,'notascc' as tabla,b.moneda,'C',a.serie,a.numero,'$ii'AS secu,LPAD(rifci,13,0) ruc,'$items_fc',
				DATE_FORMAT(fecha, '%Y%m%d')fecha,b.ccosto,c.csiigo, a.desca,'D',
				'0013'ciudad,
				if(b.moneda='01',LPAD(ROUND(a.importe,2),16,0),LPAD(ROUND(a.importe*cambio,2),16,0)) monto,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,				
				IF(b.moneda='02',LPAD(round(a.importe,2),16,0),LPAD(ROUND(a.importe/cambio,2),16,0)) montoe,	
				fecha,RPAD('$igv',4,0),'S',
				LPAD(ROUND((a.importe*'$igv'/100),2),14,0) viva,'S'	
				FROM itnotascc AS a
				JOIN notascc AS b ON a.id=b.id AND b.tipo_doc='NC'
				JOIN sinv AS c ON a.codigo=c.codigo
				WHERE id_nota='$detalle->id'"; 
						
				$this->db->query($F_c_items);
				$i++;
		}
			
		$a=$cant+3;
		
		foreach($query_2->result() as $detalle2 ){
		
		$ii =STR_PAD($a,5,0, STR_PAD_LEFT);
		$j  =STR_PAD($a,3,0, STR_PAD_LEFT);
			
				$F_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
				fdocu,  ccost, cprod,descrip,dc,cciud,cambio, monto, monto_me,fecha,pcargo,ind_tmovi,viva,met_depre)
                SELECT a.id,'notascc' as tabla,c.moneda,'C',a.serie,a.numero,'$ii'AS secu,LPAD(rifci,13,0) ruc,'2001010100',
				DATE_FORMAT(b.fecha, '%Y%m%d')fecha,b.ccosto,c.csiigo, LEFT(CONCAT(c.descrip,' ',c.descrip2),50) desca,'D',
				'0013'ciudad,INSERT(LPAD(b.cambio,12,0), 13,13, '0000') cambio,
				LPAD(round(d.costomn*d.ingreso,2),16,0) monto,
				LPAD(round(d.costome*d.ingreso,2),16,0) montoe,
				b.fecha,RPAD('$igv',4,0),'S',
				LPAD(ROUND((a.importe*'$igv'/100),2),14,0) viva,'A'	
				FROM itnotascc AS a
				JOIN notascc AS b ON a.id=b.id AND b.tipo_doc='NC'
				JOIN sinv AS c ON a.codigo=c.codigo
                JOIN costos AS d ON a.codigo=d.codigo and a.numero=d.factura and d.origen='NC'
				WHERE id_nota='$detalle2->id'"; 
						
				$this->db->query($F_c_items);
				$a++;
		}
		
		$c=$cant*2+3;
		
		foreach($query_2->result() as $detalle2 ){
		
		$ii =STR_PAD($c,5,0, STR_PAD_LEFT);
		$j  =STR_PAD($c,3,0, STR_PAD_LEFT);
			
				$F_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
				fdocu,  ccost, cprod,descrip,dc,cciud,cambio,monto,monto_me,fecha,pcargo,ind_tmovi,viva,met_depre)	
				SELECT a.id,'notascc' as tabla,c.moneda,'C',a.serie,a.numero,'$ii'AS secu,LPAD(rifci,13,0) ruc,'6901010100',
				DATE_FORMAT(b.fecha, '%Y%m%d')fecha,b.ccosto,c.csiigo, LEFT(CONCAT(c.descrip,' ',c.descrip2),50) desca,'C',
				'0013'ciudad,INSERT(LPAD(b.cambio,12,0), 13,13, '0000') cambio,
				LPAD(round(d.costomn*d.ingreso,2),16,0) monto,
				LPAD(round(d.costome*d.ingreso,2),16,0) montoe,
				b.fecha,RPAD('$igv',4,0),'S',
				LPAD(ROUND((a.importe*'$igv'/100),2),14,0) viva,'A'	
				FROM itnotascc AS a
				JOIN notascc AS b ON a.id=b.id AND b.tipo_doc='NC'
				JOIN sinv AS c ON a.codigo=c.codigo
                JOIN costos AS d ON a.codigo=d.codigo and a.numero=d.factura and d.origen='NC'
				WHERE id_nota='$detalle2->id'"; 
						
				$this->db->query($F_c_items);
				$c++;
		}
        }else{
			
			
			foreach($query_2->result() as $detalle ){
		
			$ii =STR_PAD($i,5,0, STR_PAD_LEFT);
			$j  =STR_PAD($i,3,0, STR_PAD_LEFT);
			
				$F_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
				fdocu,  ccost,descrip,dc,cciud,monto,cambio,  monto_me,fecha,pcargo,ind_tmovi,viva,met_depre)	
				SELECT a.id,'notascc' as tabla,b.moneda,'C',a.serie,a.numero,'$ii'AS secu,LPAD(rifci,13,0) ruc,a.codigo,
				DATE_FORMAT(fecha, '%Y%m%d')fecha,b.ccosto,a.desca,'D',
				'0013'ciudad,
				if(b.moneda='01',LPAD(ROUND(a.importe,2),16,0),LPAD(ROUND(a.importe*cambio,2),16,0)) monto,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,				
				IF(b.moneda='02',LPAD(round(a.importe,2),16,0),LPAD(ROUND(a.importe/cambio,2),16,0)) montoe,	
				fecha,RPAD('$igv',4,0),'S',
				LPAD(ROUND((a.importe*'$igv'/100),2),14,0) viva,'S'	
				FROM itnotascc AS a
				JOIN notascc AS b ON a.id=b.id AND b.tipo_doc='NC'
				WHERE id_nota='$detalle->id'"; 
						
				$this->db->query($F_c_items);
				
				IF($detalle->ccuenta=='9'){
					
					$a=$i+1;
					$c=$i+2;
					
					$a =STR_PAD($a,5,0, STR_PAD_LEFT);
					$c =STR_PAD($c,5,0, STR_PAD_LEFT);
					
					$ajuste=$this->datasis->dameval("SELECT ajuste FROM cpla WHERE cuenta='$detalle->cuenta'");
					
					IF (!empty($ajuste)){
						
						$F_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
						fdocu,  ccost,descrip,dc,cciud,monto,cambio,  monto_me,fecha,pcargo,ind_tmovi,viva,met_depre)	
						SELECT a.id,'notascc' as tabla,b.moneda,'C',a.serie,a.numero,'$a'AS secu,LPAD(rifci,13,0) ruc,'$ajuste',
						DATE_FORMAT(fecha, '%Y%m%d')fecha,b.ccosto,a.desca,'C',
						'0013'ciudad,
						if(b.moneda='01',LPAD(ROUND(a.importe,2),16,0),LPAD(ROUND(a.importe*cambio,2),16,0)) monto,
						INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,				
						IF(b.moneda='01',LPAD(ROUND(a.importe/cambio,2),16,0),
						LPAD(round(a.importe,2),16,0)) montoe,	
						fecha,RPAD('$igv',4,0),'S',
						LPAD(ROUND((a.importe*'$igv'/100),2),14,0) viva,'S'	
						FROM itnotascc AS a
						JOIN notascc AS b ON a.id=b.id AND b.tipo_doc='NC'
						WHERE id_nota='$detalle->id'"; 
								
						$this->db->query($F_c_items);
					}
					
					$contrapartida=$this->datasis->dameval("SELECT contrapartida FROM cpla WHERE cuenta='$detalle->cuenta'");
					
					IF (!empty($contrapartida)){
						
						$F_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
						fdocu,  ccost,descrip,dc,cciud,monto,cambio,  monto_me,fecha,pcargo,ind_tmovi,viva,met_depre)	
						SELECT a.id,'notascc' as tabla,b.moneda,'C',a.serie,a.numero,'$c'AS secu,LPAD(rifci,13,0) ruc,'$contrapartida',
						DATE_FORMAT(fecha, '%Y%m%d')fecha,b.ccosto,a.desca,'D',
						'0013'ciudad,
						if(b.moneda='01',LPAD(ROUND(a.importe,2),16,0),LPAD(ROUND(a.importe*cambio,2),16,0)) monto,
						INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,				
						IF(b.moneda='01',LPAD(ROUND(a.importe/cambio,2),16,0),
						LPAD(round(a.importe,2),16,0)) montoe,	
						fecha,RPAD('$igv',4,0),'S',
						LPAD(ROUND((a.importe*'$igv'/100),2),14,0) viva,'S'	
						FROM itnotascc AS a
						JOIN notascc AS b ON a.id=b.id AND b.tipo_doc='NC'
						WHERE id_nota='$detalle->id'"; 
								
						$this->db->query($F_c_items);
					}
				
				}
				
				$i++;
			}		
		
		}
		}
		//****************************************************
		//Notas de Credito Saldo de Proveedores
		
		$query=$this->db->query("SELECT id,iva FROM notascp WHERE fecha BETWEEN '$fechai' AND '$fechaf'AND tipo_doc='NC' AND almacen='0000'");
		
		foreach($query->result() as $items ){
			
		$query_2=$this->db->query("SELECT id_nota as id,cuenta,LPAD(cuenta,1,1) as ccuenta FROM itnotascp WHERE id='$items->id'");
		$cant=$this->datasis->dameval("SELECT COUNT(*) FROM itnotascp WHERE id='$items->id'");
		
		//$m1=$cant+1;
		//$m2=$cant+2;
		//
		//$m1=STR_PAD($m1,5,0, STR_PAD_LEFT);	
		//$m2=STR_PAD($m2,5,0, STR_PAD_LEFT);
		
		$F_d_cc="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
		fdocu,  ccost, descrip,  dc,cciud,  monto,    
		cambio,  monto_me, tdoc_cruce,ccomp_cruce,num_cruce,sec_cruce,fven_cruce,formap, fecha)
		SELECT a.id,'notascp' as tabla,moneda,'C',a.serie,a.numero,'00001'AS secu,LPAD(rifci,13,0) ruc,cuenta,
		DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto,
		CONCAT('CUENTA POR PAGAR ',a.serie,'-',a.numero) descrip,'D','0013',
		if(a.moneda='01',LPAD(ROUND(a.totalg,2),16,0),LPAD(ROUND(a.totalg*cambio,2),16,0)) monto,
		INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(a.moneda='01',LPAD(ROUND(a.totalg/a.cambio,2),16,0),
		LPAD(a.totalg,16,0)) montoe,'F',serief,factura,'001',DATE_FORMAT(fechaf, '%Y%m%d')vence,
		LPAD(formap,4,0) cod_formap,fecha	
		FROM notascp AS a WHERE tipo_doc='NC'
		AND id='$items->id'";
				
		$this->db->query($F_d_cc);	
		
		
		IF($items->iva >0){
				
		$F_c_iva="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
		fdocu,  ccost, descrip,  dc,  monto,    
		cambio,  monto_me,fecha)			
		SELECT a.id,'notascp' as tabla,moneda,'C',a.serie,a.numero,'00002'AS secu,LPAD(rifci,13,0) ruc,'$iva',
		DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto,
		CONCAT('IVA DEL DOCUMENTO ',a.serie,'-',a.numero) descrip,'C',
		if(a.moneda='01',LPAD(ROUND(a.iva,2),16,0),LPAD(ROUND(a.iva*cambio,2),16,0)) monto,
		INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(a.moneda='01',LPAD(ROUND(a.iva/a.cambio,2),16,0),LPAD(a.iva,16,0)) montoe,fecha	
		FROM notascp AS a WHERE tipo_doc='NC'
		AND id='$items->id'";
		
		$this->db->query($F_c_iva);
		
		}
		
		$i=3;	
						
		foreach($query_2->result() as $detalle ){
		
		$ii =STR_PAD($i,5,0, STR_PAD_LEFT);
		$j  =STR_PAD($i,3,0, STR_PAD_LEFT);
			
				$F_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
				fdocu,  ccost, descrip,dc,cciud,monto,cambio,  monto_me,fecha,pcargo,ind_tmovi,viva,met_depre)	
				SELECT a.id,'notascp' as tabla,b.moneda,'C',a.serie,a.numero,'$ii'AS secu,LPAD(rifci,13,0) ruc,a.cuenta,
				DATE_FORMAT(fecha, '%Y%m%d')fecha,b.ccosto,a.descrip,'C','0013'ciudad,
				if(b.moneda='01',LPAD(ROUND(a.total,2),16,0),LPAD(ROUND(a.total*cambio,2),16,0)) monto,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,				
				IF(b.moneda='01',LPAD(ROUND(a.total/cambio,2),16,0),
				LPAD(round(a.total,2),16,0)) montoe,	
				fecha,RPAD('$igv',4,0),'S',
				LPAD(ROUND((a.total*'$igv'/100),2),14,0) viva,'S'	
				FROM itnotascp AS a
				JOIN notascp AS b ON a.id=b.id AND b.tipo_doc='NC'
				WHERE id_nota='$detalle->id'"; 
						
				$this->db->query($F_c_items);
				
				IF($detalle->ccuenta=='9'){
					
					$a=$i+1;
					$c=$i+2;
					
					$a =STR_PAD($a,5,0, STR_PAD_LEFT);
					$c =STR_PAD($c,5,0, STR_PAD_LEFT);
					
					$ajuste=$this->datasis->dameval("SELECT ajuste FROM cpla WHERE cuenta='$detalle->cuenta'");
					
					IF (!empty($ajuste)){
						
						$F_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
						fdocu,  ccost, descrip,dc,cciud,monto,cambio,  monto_me,fecha,pcargo,ind_tmovi,viva,met_depre)	
						SELECT a.id,'notascp' as tabla,b.moneda,'C',a.serie,a.numero,'$a'AS secu,LPAD(rifci,13,0) ruc,'$ajuste',
						DATE_FORMAT(fecha, '%Y%m%d')fecha,b.ccosto,a.descrip,'C',
						'0013'ciudad,
						if(b.moneda='01',LPAD(ROUND(a.total,2),16,0),LPAD(ROUND(a.total*cambio,2),16,0)) monto,
						INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,				
						IF(b.moneda='01',LPAD(ROUND(a.total/cambio,2),16,0),
						LPAD(round(a.total,2),16,0)) montoe,	
						fecha,RPAD('$igv',4,0),'S',
						LPAD(ROUND((a.total*'$igv'/100),2),14,0) viva,'S'	
						FROM itnotascp AS a
						JOIN notascp AS b ON a.id=b.id AND b.tipo_doc='NC'
						WHERE id_nota='$detalle->id'"; 
								
						$this->db->query($F_c_items);
					}
					
					$contrapartida=$this->datasis->dameval("SELECT contrapartida FROM cpla WHERE cuenta='$detalle->cuenta'");
					
					IF (!empty($contrapartida)){
						
						$F_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
						fdocu,  ccost, descrip,dc,cciud,monto,cambio,  monto_me,fecha,pcargo,ind_tmovi,viva,met_depre)	
						SELECT a.id,'notascp' as tabla,b.moneda,'C',a.serie,a.numero,'$c'AS secu,LPAD(rifci,13,0) ruc,'$contrapartida',
						DATE_FORMAT(fecha, '%Y%m%d')fecha,b.ccosto,a.descrip,'D',
						'0013'ciudad,
						if(b.moneda='01',LPAD(ROUND(a.total,2),16,0),LPAD(ROUND(a.total*cambio,2),16,0)) monto,
						INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,				
						IF(b.moneda='01',LPAD(ROUND(a.total/cambio,2),16,0),
						LPAD(round(a.total,2),16,0)) montoe,	
						fecha,RPAD('$igv',4,0),'S',
						LPAD(ROUND((a.total*'$igv'/100),2),14,0) viva,'S'	
						FROM itnotascp AS a
						JOIN notascp AS b ON a.id=b.id AND b.tipo_doc='NC'
						WHERE id_nota='$detalle->id'"; 
								
						$this->db->query($F_c_items);
					}
				
				}
				
				$i++;
            }
        
        }
        
        //****************************************************
		//Notas de Credito de Productos devueltos por Proveedores
		
		$query=$this->db->query("SELECT id,iva,proveed FROM notascp WHERE fecha BETWEEN '$fechai' AND '$fechaf'AND tipo_doc='NC'  AND almacen<>'0000'");
		
		foreach($query->result() as $items ){
			
		$query_2=$this->db->query("SELECT id_nota as id FROM itnotascp WHERE id='$items->id'");
		$cant=$this->datasis->dameval("SELECT COUNT(*) FROM itnotascp WHERE id='$items->id'");
		$origen=$this->datasis->dameval("SELECT tiva FROM sprv WHERE proveed='$items->proveed'");
		
		if($origen=='I'){
			$m1=$cant*4+1;
		}else{
			$m1=$cant*3+1;
		}
				
		$m1=STR_PAD($m1,5,0, STR_PAD_LEFT);		
				
		$F_d_cc="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
		fdocu,  ccost, descrip,  dc,cciud,  monto,    
		cambio,  monto_me, tdoc_cruce,ccomp_cruce,num_cruce,sec_cruce,fven_cruce,formap, fecha)
		SELECT a.id,'notascp' as tabla,moneda,'C',a.serie,a.numero,'$m1'AS secu,LPAD(rifci,13,0) ruc,cuenta,
		DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto,
		CONCAT('CUENTA POR PAGAR ',a.serie,'-',a.numero) descrip,'D','0013',
		if(a.moneda='01',LPAD(ROUND(a.totalg,2),16,0),LPAD(ROUND(a.totalg*cambio,2),16,0)) monto,
		INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(a.moneda='01',LPAD(ROUND(a.totalg/a.cambio,2),16,0),
		LPAD(a.totalg,16,0)) montoe,'F',serief,factura,'001',DATE_FORMAT(fechaf, '%Y%m%d')vence,
		LPAD(formap,4,0) cod_formap,fecha	
		FROM notascp AS a WHERE tipo_doc='NC'
		AND id='$items->id'";
				
		$this->db->query($F_d_cc);	
		
		IF($items->iva >0){	
			
		if($origen=='I'){
			$m2=$cant*4+2;
		}else{
			$m2=$cant*3+2;
		}
		
		$m2=STR_PAD($m2,5,0, STR_PAD_LEFT);
		
		$F_c_iva="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
		fdocu,  ccost, descrip,  dc,  monto,    
		cambio,  monto_me,fecha)			
		SELECT a.id,'notascp' as tabla,moneda,'C',a.serie,a.numero,'$m2'AS secu,LPAD(rifci,13,0) ruc,'$iva',
		DATE_FORMAT(fecha, '%Y%m%d')fecha,ccosto,
		CONCAT('IVA DEL DOCUMENTO ',a.serie,'-',a.numero) descrip,'C',
		if(a.moneda='01',LPAD(ROUND(a.iva,2),16,0),LPAD(ROUND(a.iva*cambio,2),16,0)) monto,
		INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(a.moneda='01',LPAD(ROUND(a.iva/a.cambio,2),16,0),LPAD(a.iva,16,0)) montoe,fecha	
		FROM notascp AS a WHERE tipo_doc='NC'
		AND id='$items->id'";
		
		$this->db->query($F_c_iva);
		
		}
		
		if($origen=='I'){
			
		$m3=$cant*3+1;
			
		foreach($query_2->result() as $detalle ){
			    
            $m3=STR_PAD($m3,5,0, STR_PAD_LEFT);
            
            if($origen=='I'){
				
				$F_c_items4="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
				fdocu,  ccost, descrip,dc,cciud,monto,cambio,  monto_me,fecha,pcargo,ind_tmovi,viva,met_depre,cprod)	
				SELECT a.id,'notascp' as tabla,b.moneda,'C',a.serie,a.numero,'$m3'AS secu,LPAD(rifci,13,0) ruc,'2801011100' cuenta,
				DATE_FORMAT(fecha, '%Y%m%d')fecha,b.ccosto,c.descrip,'C',
				'0013'ciudad,
				if(b.moneda='01',LPAD(ROUND(a.total,2),16,0),LPAD(ROUND(a.total*cambio,2),16,0)) monto,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,				
				IF(b.moneda='01',LPAD(ROUND(a.total/cambio,2),16,0),
				LPAD(round(a.total,2),16,0)) montoe,	
				fecha,RPAD('$igv',4,0),'S',
				LPAD(ROUND((a.total*'$igv'/100),2),14,0) viva,'S',c.csiigo	
				FROM itnotascp AS a
				JOIN notascp AS b ON a.id=b.id AND b.tipo_doc='NC'
				JOIN sinv as c on a.cuenta=c.codigo
				WHERE id_nota='$detalle->id'"; 
						
				$this->db->query($F_c_items4);
				$m3++;
				
			}
			
		}
		
		}else{
		
	   $m4=-1;
	   $m5=0;
	   $m6=1;
						
	   foreach($query_2->result() as $detalle ){

	   $m4=$m4+2;
	   $m5=$m5+2; 
       $m6=$m6+2;
       
       $m4=STR_PAD($m4,5,0, STR_PAD_LEFT); 
       $m5=STR_PAD($m5,5,0, STR_PAD_LEFT);
       $m6=STR_PAD($m6,5,0, STR_PAD_LEFT);
					
			
				$F_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
				fdocu,  ccost, descrip,dc,cciud,monto,cambio,  monto_me,fecha,pcargo,ind_tmovi,viva,met_depre,cprod)	
				SELECT a.id,'notascp' as tabla,b.moneda,'C',a.serie,a.numero,'$m4'AS secu,LPAD(rifci,13,0) ruc,'2001010100' cuenta,
				DATE_FORMAT(fecha, '%Y%m%d')fecha,b.ccosto,c.descrip,'C',
				'0013'ciudad,
				if(b.moneda='01',LPAD(ROUND(a.total,2),16,0),LPAD(ROUND(a.total*cambio,2),16,0)) monto,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,				
				IF(b.moneda='01',LPAD(ROUND(a.total/cambio,2),16,0),LPAD(round(a.total,2),16,0)) montoe,	
				fecha,RPAD('$igv',4,0),'S',
				LPAD(ROUND((a.total*'$igv'/100),2),14,0) viva,'S',c.csiigo	
				FROM itnotascp AS a
				JOIN notascp AS b ON a.id=b.id AND b.tipo_doc='NC'
				JOIN sinv as c on a.cuenta=c.codigo
				WHERE id_nota='$detalle->id'"; 
						
				$this->db->query($F_c_items);
				
				$F_c_items2="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
				fdocu,  ccost, descrip,dc,cciud,monto,cambio,  monto_me,fecha,pcargo,ind_tmovi,viva,met_depre,cprod)	
				SELECT a.id,'notascp' as tabla,b.moneda,'C',a.serie,a.numero,'$m5'AS secu,LPAD(rifci,13,0) ruc,'6001010000' cuenta,
				DATE_FORMAT(fecha, '%Y%m%d')fecha,b.ccosto,c.descrip,'C',
				'0013'ciudad,
				if(b.moneda='01',LPAD(ROUND(a.total,2),16,0),LPAD(ROUND(a.total*cambio,2),16,0)) monto,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,				
				IF(b.moneda='01',LPAD(ROUND(a.total/cambio,2),16,0),
				LPAD(round(a.total,2),16,0)) montoe,	
				fecha,RPAD('$igv',4,0),'S',
				LPAD(ROUND((a.total*'$igv'/100),2),14,0) viva,'S',c.csiigo	
				FROM itnotascp AS a
				JOIN notascp AS b ON a.id=b.id AND b.tipo_doc='NC'
				JOIN sinv as c on a.cuenta=c.codigo
				WHERE id_nota='$detalle->id'"; 
						
				$this->db->query($F_c_items2);
				
				$F_c_items3="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,cuenta,  
				fdocu,  ccost, descrip,dc,cciud,monto,cambio,  monto_me,fecha,pcargo,ind_tmovi,viva,met_depre,cprod)	
				SELECT a.id,'notascp' as tabla,b.moneda,'C',a.serie,a.numero,'$m6'AS secu,LPAD(rifci,13,0) ruc,'6101010000' cuenta,
				DATE_FORMAT(fecha, '%Y%m%d')fecha,b.ccosto,c.descrip,'D',
				'0013'ciudad,
				if(b.moneda='01',LPAD(ROUND(a.total,2),16,0),LPAD(ROUND(a.total*cambio,2),16,0)) monto,
				INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,				
				IF(b.moneda='01',LPAD(ROUND(a.total/cambio,2),16,0),
				LPAD(round(a.total,2),16,0)) montoe,	
				fecha,RPAD('$igv',4,0),'S',
				LPAD(ROUND((a.total*'$igv'/100),2),14,0) viva,'S',c.csiigo	
				FROM itnotascp AS a
				JOIN notascp AS b ON a.id=b.id AND b.tipo_doc='NC'
				JOIN sinv as c on a.cuenta=c.codigo
				WHERE id_nota='$detalle->id'"; 
						
				$this->db->query($F_c_items3);
								
				$m4++;
				$m5++;
				$m6++;
								
            }
         }
        
        }
    }
    function _p($fechai,$fechaf){
        
        $iva=$this->cuenta->iva();
		$igv=$this->datasis->traevalor('IGV');
        
        $this->db->query("DELETE FROM comprobantes WHERE tcomp IN ('P','D') AND fecha BETWEEN '$fechai' AND '$fechaf' AND tabla<>'siigo' AND tabla IN ('gser')");
        
        //****************************************************
		//Facturas de Gasto
		
		$query=$this->db->query("SELECT transac FROM gser WHERE recepcion BETWEEN '$fechai' AND '$fechaf' AND comp<>'L'");
		
		foreach($query->result() as $items ){
			
		$query_2=$this->db->query("SELECT id,cuenta,transac FROM gitser WHERE transac='$items->transac'");
		$cant   =$this->datasis->dameval("SELECT COUNT(*) FROM gitser WHERE transac='$items->transac'");
		$cuenta =$this->datasis->dameval("SELECT cuenta FROM gitser WHERE transac='$items->transac' LIMIT 1");
		$viva   =$this->datasis->dameval("SELECT totiva FROM gser WHERE transac='$items->transac'");
		$comp   =$this->datasis->dameval("SELECT comp FROM gser WHERE transac='$items->transac'");
		
		IF($viva>0){
			$vigv=$igv;
			$ind_tmovi='S';
			$coa='S';
			
		}else{
			
			$vigv=0;
			$ind_tmovi='B';
			$coa='B';
			
		}
		
		$m1=$cant+1;
		$m2=$cant+2;
		$m3=$cant+3;
		$m4=$cant+4;
		
		$m1=STR_PAD($m1,5,0, STR_PAD_LEFT);	
		$m2=STR_PAD($m2,5,0, STR_PAD_LEFT);
		$m3=STR_PAD($m3,5,0, STR_PAD_LEFT);
		$m4=STR_PAD($m4,5,0, STR_PAD_LEFT);
		  
		$P_c_cp="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,  cuenta,tdoc_cruce,ccomp_cruce,num_cruce,sec_cruce,fven_cruce,
		fdocu,  ccost, descrip,  dc,  monto,  cvend, cambio,  monto_me,fecha,formap,ncom_prov,ndoc_prov,fdoc_prov,cpago)
		SELECT a.transac,'gser' as tabla,moneda,IF(comp='ND','D','P')comp,IF(comp='ND','002',a.seriei)seriei,a.numeroi,'$m1'AS secu,LPAD(rif,13,0) ruc,'000'sucu,cuenta,'P',a.seriep,a.numero,'001'secu,DATE_FORMAT(a.vence, '%Y%m%d')fecha,
		DATE_FORMAT(a.recepcion, '%Y%m%d')fecha,ccosto, 
		CONCAT('CUENTA POR PAGAR ',seriep,'-',numero)descrip,'C',
		if(a.moneda='01',LPAD(ROUND(a.totbruto,2),16,0),LPAD(ROUND(a.totbruto*cambio,2),16,0)) monto,
		'0000'vd,INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
		IF(moneda='01',LPAD(ROUND(a.totbruto/cambio,2),16,0),LPAD(a.totbruto,16,0)) montoe,a.recepcion,LPAD(formap,4,0),
		LPAD(a.seriep,4,0),a.numero,DATE_FORMAT(a.fecha, '%Y%m%d')fecha,a.numero		
		FROM gser AS a
		WHERE a.transac='$items->transac'";
		
		$this->db->query($P_c_cp);
		
		IF($viva>0){
		
			$P_c_iva="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,cuenta,tdoc_cruce,ccomp_cruce,num_cruce,sec_cruce,fven_cruce,  
			fdocu,  ccost, descrip,  dc,  monto,  cvend, cambio,  monto_me,fecha,ncom_prov,ndoc_prov,fdoc_prov,cpago)
			SELECT a.transac,'gser' as tabla,moneda,IF(comp='ND','D','P')comp,IF(comp='ND','002',a.seriei)seriei,a.numeroi,'$m2'AS secu,LPAD(rif,13,0) ruc,'000'sucu,'$iva','P',a.seriep,a.numero,'001'secu,DATE_FORMAT(a.vence, '%Y%m%d')fecha,
			DATE_FORMAT(a.recepcion, '%Y%m%d')fecha,ccosto, 
			CONCAT('IVA DEL DOCUMENTO ',seriep,'-',numero)descrip,'D',
			if(a.moneda='01',LPAD(ROUND(a.totiva,2),16,0),LPAD(ROUND(a.totiva*cambio,2),16,0)) monto,
			'0000'vd,INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			IF(moneda='01',LPAD(ROUND(a.totiva/cambio,2),16,0),LPAD(a.totiva,16,0)) montoe,a.recepcion,
			LPAD(a.seriep,4,0),a.numero,DATE_FORMAT(a.fecha, '%Y%m%d')fecha,a.numero
			FROM gser AS a
			WHERE a.transac='$items->transac'";
			
			$this->db->query($P_c_iva);
		
		}
		
		IF($viva>0){
		
			$m3=$m3-1;
			$m4=$m4-1;
		
		}else{
			
			$m3=$m2-1;
			$m4=$m2;	
		}
		
       $query_1=$this->db->query("SELECT b.id,b.transac,b.cuenta FROM gitser as b JOIN gser as a ON a.transac=b.transac 
       WHERE b.transac='$items->transac' AND b.cuenta like '9%'");
       
       foreach($query_1->result() as $items1 ){
              
       $m4=$m4+1; 
       $m3=$m3+1;
       
       $m3=STR_PAD($m3,5,0, STR_PAD_LEFT);
       $m4=STR_PAD($m4,5,0, STR_PAD_LEFT); 
           		
			$ajuste=$this->datasis->dameval("SELECT ajuste FROM cpla WHERE cuenta='$items1->cuenta'");
			
            IF (!empty($ajuste)){		
			
            $P_aj="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,  cuenta,  
			fdocu,  ccost, descrip,  dc,  monto,  cvend,cambio,  monto_me, fecha,ind_tmovi,piva,viva,ncom_prov,ndoc_prov,fdoc_prov,cpago,met_depre,pcargo,fven_cruce)
			SELECT a.transac,'gser' as tabla,moneda,IF(comp='ND','D','P')comp,a.seriei,a.numeroi,'$m3'AS secu,LPAD(rif,13,0) ruc,'000'sucu,'$ajuste',
			DATE_FORMAT(a.recepcion, '%Y%m%d')fecha,ccosto, 
            IF(b.tipo='D',IF(condi1<>'',LEFT(condi1,50),desca),LEFT(desca,50))as descrip,'D',
			if(a.moneda='01',LPAD(ROUND(b.preca,2),16,0),LPAD(ROUND(b.preca*cambio,2),16,0)) monto,
			'0000'vd,INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			IF(moneda='01',LPAD(ROUND(b.preca/cambio,2),16,0),LPAD(b.preca,16,0)) montoe,
			a.recepcion,'$ind_tmovi',RPAD('$vigv',4,0) as piva,LPAD(ROUND((b.preca*'$vigv'/100),2),14,0) viva,LPAD(a.seriep,4,0),a.numero,DATE_FORMAT(a.fecha, '%Y%m%d')fecha,a.numero,'$coa',RPAD('$vigv',4,0) as pcargo,	
			DATE_FORMAT(a.vence, '%Y%m%d')fecha
			FROM gser AS a
			JOIN gitser AS b ON a.transac=b.transac
			WHERE a.transac='$items1->transac' and b.id='$items1->id'";
			
			$this->db->query($P_aj);
            
            }
			
			$contrapartida=$this->datasis->dameval("SELECT contrapartida FROM cpla WHERE cuenta='$items1->cuenta'");
			
            IF (!empty($contrapartida)){
                
			$P_cont="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,  cuenta,  
			fdocu,  ccost, descrip,  dc,  monto,  cvend,cambio,  monto_me, fecha,ind_tmovi,piva,viva,ncom_prov,ndoc_prov,fdoc_prov,cpago,met_depre,pcargo,fven_cruce)
			SELECT a.transac,'gser' as tabla,moneda,IF(comp='ND','D','P')comp,a.seriei,a.numeroi,'$m4'AS secu,LPAD(rif,13,0) ruc,'000'sucu,'$contrapartida',
			DATE_FORMAT(a.recepcion, '%Y%m%d')fecha,ccosto, 
			CONCAT('CARGOS IMPUTABLES A CUENTAS DE COSTOS ')descrip,'C',
			if(a.moneda='01',LPAD(ROUND(b.preca,2),16,0),LPAD(ROUND(b.preca*cambio,2),16,0)) monto,
			'0000'vd,INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			IF(moneda='01',LPAD(ROUND(b.preca/cambio,2),16,0),LPAD(b.preca,16,0)) montoe,
			a.recepcion,'$ind_tmovi',RPAD('$vigv',4,0) as piva,LPAD(ROUND((b.preca*'$vigv'/100),2),14,0) viva,LPAD(a.seriep,4,0),a.numero,DATE_FORMAT(a.fecha, '%Y%m%d')fecha,a.numero,'$coa',RPAD('$vigv',4,0) as pcargo,	
			DATE_FORMAT(a.vence, '%Y%m%d')fecha
			FROM gser AS a
			JOIN gitser AS b ON a.transac=b.transac
			WHERE a.transac='$items1->transac' and b.id='$items1->id'";
					
			$this->db->query($P_cont);	
            
            }
            
            $m3++;
            $m4++;
        }
		
		$i=1;	
						
		foreach($query_2->result() as $detalle ){
		
			$i=STR_PAD($i,5,0, STR_PAD_LEFT);
		
			$P_c_items="INSERT INTO comprobantes (id,tabla,moneda_origen,tcomp,  ccomp,  ncomp,  secuencia,  nit,  sucursal,  cuenta,  
			fdocu,  ccost, descrip,  dc,  monto,  cvend,cambio,  monto_me, fecha,ind_tmovi,piva,viva,ncom_prov,ndoc_prov,fdoc_prov,cpago,met_depre,pcargo,fven_cruce)
			SELECT a.transac,'gser' as tabla,moneda,IF(comp='ND','D','P')comp,IF(comp='ND','002',a.seriei)seriei,a.numeroi,'$i'AS secu,LPAD(rif,13,0) ruc,'000'sucu,b.cuenta,
			DATE_FORMAT(a.recepcion, '%Y%m%d')fecha,ccosto, 
            IF(b.tipo='D',IF(condi1<>'',LEFT(condi1,50),desca),LEFT(desca,50))as desca,b.tipo,
			if(a.moneda='01',LPAD(ROUND(b.preca,2),16,0),LPAD(ROUND(b.preca*cambio,2),16,0)) monto,
			'0000'vd,INSERT(LPAD(cambio,12,0), 13,13, '0000') cambio,
			IF(moneda='01',LPAD(ROUND(b.preca/cambio,2),16,0),LPAD(b.preca,16,0)) montoe,
			a.recepcion,'$ind_tmovi',RPAD('$vigv',4,0) as piva,LPAD(ROUND((b.preca*'$vigv'/100),2),14,0) viva,LPAD(a.seriep,4,0),a.numero,DATE_FORMAT(a.fecha, '%Y%m%d')fecha,a.numero,'$coa',RPAD('$vigv',4,0) as pcargo,	
			DATE_FORMAT(a.vence, '%Y%m%d')fecha
			FROM gser AS a
			JOIN gitser AS b ON a.transac=b.transac
			WHERE b.id='$detalle->id'";
			
			$this->db->query($P_c_items);	
		
			$i++;
		}		
			
        }
        
    }
}
?>
